package mainimport ( "time" "fmt")//ticker是一个定时触发的计时器,它会以一个间隔往channel发送整一个事件(当时时间),而channel的接收者可以以固定的时间间隔从channel中读取事件func main() { ticker := time.NewTicker(time.Second) i := 0 for true { time := <-ticker.C i++ fmt.Printf("i = %d, time = %v\n", i, time) if i==5 { ticker.Stop() break } }}
执行的结果为
i = 1, time = 2018-09-20 09:22:38.9705836 +0800 CST m=+1.001708201i = 2, time = 2018-09-20 09:22:39.9702884 +0800 CST m=+2.001413001i = 3, time = 2018-09-20 09:22:40.9699923 +0800 CST m=+3.001116901i = 4, time = 2018-09-20 09:22:41.970699 +0800 CST m=+4.001823601i = 5, time = 2018-09-20 09:22:42.9704029 +0800 CST m=+5.001527501