详情可参考:[gitea](https://gitea.com/4fun/study_everyday/src/branch/master/timer)
#### 场景一
``` go
ticker := time.NewTicker(2e9)
defer ticker.Stop()
// 添加一个channel用来实现定时效果
stop := make(chan bool)
// 为了测试方便,改为4秒。
time.AfterFunc(time.Second*4, func() {
stop <- true
})
for {
select {
case <-ticker.C:
log.Println("hello study golang")
case <-stop:
return
default:
}
}
```
#### 场景二
``` go
func IGoHome() {
// 为了方便测试,30 分钟改为 10秒
ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
maxPersons := make([]*Person, 0, 7)
var stop sync.Once
var start sync.Once
for {
// 判断是否在 7 点到 20 点之间
if !betweenWorkTime() {
stop.Do(printNotWork)
continue
}
start.Do(printWork)
person, ok := NewPersonComming()
if ok {
maxPersons = append(maxPersons, person)
} else {
time.Sleep(2e9)
}
select {
case <-ticker.C:
// 时间已到,发车
CarMoving(maxPersons)
default:
// 时间未到,判断是否坐满
if len(maxPersons) == 7 {
CarMoving(maxPersons)
maxPersons = make([]*Person, 0, 7)
}
}
}
}
// betweenWorkTime returns if it is between start time and end time.
func betweenWorkTime() bool {
now := time.Now()
start := time.Date(now.Year(), now.Month(), now.Day(), 7, 0, 0, 0, now.Location())
stop := time.Date(now.Year(), now.Month(), now.Day(), 20, 0, 0, 0, now.Location())
if time.Now().Before(start) {
return false
}
if time.Now().After(stop) {
return false
}
return true
}
func printNotWork() {
fmt.Println("正在歇班,请耐心等待~")
}
func printWork() {
fmt.Println("开工了!")
}
func NewPersonComming() (*Person, bool) {
if rand.Intn(4) == 0 {
return nil, false
}
var builder strings.Builder
for i := 0; i < 4; i++ {
builder.WriteByte(chars[rand.Intn(26)])
}
fmt.Println(builder.String(), " is coming!")
return &Person{Name: builder.String()}, true
}
func CarMoving(maxPersons []*Person) {
fmt.Println("==================")
fmt.Println("The car is moving, is full or not?", len(maxPersons) == 7)
fmt.Print("They are: ")
for _, person := range maxPersons {
fmt.Print(person.Name, "\t")
}
fmt.Println("\n==================")
}
```
一个简单的例子如下:
![定时器-7至20点工作.png](https://static.studygolang.com/190717/6b852a94872ddde296e7861eaf24c794.png)
欢迎交流~
#1
更多评论