Golang——time.Ticker定时器

ticker一般用来作为时间周期执行命令:

func main() {
ticker := time.NewTicker(time.Second) // 每隔1s进行一次打印
for {
<-ticker.C
fmt.Println("这是ticker的打印")
}
}

Ticker结构体

// A Ticker holds a channel that delivers ``ticks'' of a clock
// at intervals.
type Ticker struct {
C <-chan Time // The channel on which the ticks are delivered.
r runtimeTimer
}

Ticker保管一个​​通道​​,并每隔一段时间向其传递"tick"。

创建时钟周期

time.NewTicker()

func NewTicker(d Duration) *Ticker
NewTicker返回一个新的Ticker,该Ticker包含一个通道字段,并会每隔时间段d就向该通道发送当时的时间。它会调整时间间隔或者丢弃tick信息以适应反应慢的接收者。如果d<=0会panic。关闭该Ticker可以释放相关资源

实例1:在11点35分打印"Golang"

func main() {
myTicker:=time.NewTicker(time.Second) //设置时间周期
for{
nowTime:=<-myTicker.C //当前时间
if nowTime.Hour()==11 && nowTime.Minute()==35{
fmt.Println("Golang")
break
}
}
}

实例2:每秒打印时间,然后10秒后结束。

package main

import (
"fmt"
"time"
)

func main() {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
done := make(chan bool)
go func() {
time.Sleep(10 * time.Second)
done <- true
}()
for {
select {
case <-done:
fmt.Println("Done!")
return
case t := <-ticker.C:
fmt.Println("Current time: ", t)
}
}
}

输出结果

Current time:  2022-10-21 09:52:47.7603062 +0800 CST m=+1.029829101
Current time: 2022-10-21 09:52:48.7591099 +0800 CST m=+2.028632801
Current time: 2022-10-21 09:52:49.7620993 +0800 CST m=+3.031622201
Current time: 2022-10-21 09:52:50.7534455 +0800 CST m=+4.022968401
Current time: 2022-10-21 09:52:51.7596767 +0800 CST m=+5.029199601
Current time: 2022-10-21 09:52:52.7634561 +0800 CST m=+6.032979001
Current time: 2022-10-21 09:52:53.7499603 +0800 CST m=+7.019483201
Current time: 2022-10-21 09:52:54.7570725 +0800 CST m=+8.026595401
Current time: 2022-10-21 09:52:55.7489688 +0800 CST m=+9.018491701
Done!

使用Tick()方法

// Tick is a convenience wrapper for NewTicker providing access to the ticking
// channel only. While Tick is useful for clients that have no need to shut down
// the Ticker, be aware that without a way to shut it down the underlying
// Ticker cannot be recovered by the garbage collector; it "leaks".
// Unlike NewTicker, Tick will return nil if d <= 0.
func Tick(d Duration) <-chan Time {
if d <= 0 {
return nil
}
return NewTicker(d).C
}

实例

// 60秒定期更新一次
tick := time.Tick(60 * time.Second)
go func() {
for {
<-tick
err = do_something(...)
if err != nil {
panic(err)
}
}
}()

参考文章

​传送门1​

​传送门2​