当我们想按固定的时间间隔进行一些工作时, 会使用“ Go Tickers”。可以使用Stop()方法像停止计时器一样停止ticker。
NewTicker()方法返回一个新的Ticker, 该Ticker具有一个根据duration参数发送时间的通道。持续时间必须大于零, 否则, 置顶器将出现panic。
Tick()是NewTicker的包装, 它提供对滴答通道的访问。 Tick()方法对于不想关闭ticker指示器的客户很有用。
Go ticker示例
package main
import "time"
import "fmt"
func main() {
tickerValue := time.NewTicker(time.Millisecond * 100)
go func() {
for t := range tickerValue.C {
fmt.Println("Tick at", t)
}
}()
time.Sleep(time.Millisecond * 500)
tickerValue.Stop()
fmt.Println("Ticker stopped")
}
输出:
Tick at 2017-10-07 17:26:35.946279716 +0530 IST m=+0.101345812
Tick at 2017-10-07 17:26:36.046371811 +0530 IST m=+0.201437907
Tick at 2017-10-07 17:26:36.146417657 +0530 IST m=+0.301483753
Tick at 2017-10-07 17:26:36.24851386 +0530 IST m=+0.403579956
Tick at 2017-10-07 17:26:36.346476978 +0530 IST m=+0.501543074
Ticker stopped
Go代码示例2
package main
import (
"log"
"time"
)
func haveFun(s string) {
log.Printf("\tA: Let's have fun: %v", s)
}
func doPolling() {
for _ = range time.Tick(2 * time.Second) {
haveFun("\t B : Okay!")
}
}
func main() {
go doPolling()
select {} //The select statement lets a goroutine wait on multiple communication operations.
}
输出:
2017/10/07 18:15:15 A: Let's have fun: B : Okay!
2017/10/07 18:15:17 A: Let's have fun: B : Okay!
2017/10/07 18:15:19 A: Let's have fun: B : Okay!
2017/10/07 18:15:21 A: Let's have fun: B : Okay!
2017/10/07 18:15:23 A: Let's have fun: B : Okay!
2017/10/07 18:15:25 A: Let's have fun: B : Okay!