Go 定时器/延时触发器
文章目录
Go 可以借助 time.After/time.Ticker 来实现延迟/定时触发器,主要原理是借助无缓冲channel无数据时读取操作会阻塞当前协程,Go会在给定的时间后向channel中写入一些数据(当前时间),故阻塞的协程可以恢复运行,达到延迟或定时执行的功能。
延迟执行
time.After(d Duration) 好像不如直接用 time.Sleep(d Duration)舒服,但存在即合理,time.After(d Duration)的强大之处在于是基于channel的,可以在不同的协程间同步传递。
package main
import (
"time"
"fmt"
)
func main() {
fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
// create a nobuf channel and a goroutine `timer` will write it after 2 seconds
timeAfterTrigger = time.After(time.Second * 2)
// will be suspend but we have `timer` so will be not deadlocked
curTime, _ := <-timeAfterTrigger
// print current time
fmt.Println(curTime.Format("2006-01-02 15:04:05"))
}
定时执行
time.Ticker 的使用分两种场景:执行几次后退出 和 循环执行不退出,执行几次就退出的话我们需要需要回收 time.Ticker。
执行若干次后退出需清理计时器
func main() {
// 创建一个计时器
timeTicker := time.NewTicker(time.Second * 2)
i := 0
for {
if i > 5 {
break
}
fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
i++
<-timeTicker.C
}
// 清理计时器
timeTicker.Stop()
}
循环执行不需要清理的话可以用更简便的time.Tick()方法
func main() {
// 创建一个计时器
timeTickerChan := time.Tick(time.Second * 2)
for {
fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
<-timeTickerChan
}
}

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论