go 开启定时任务

最近在弄websocket,然后其中需要定时发送心跳数据,记录下go如何弄定时任务

首先下载一个定时任务库

go get github.com/robfig/cron/v3

然后下面上代码,其实还是挺简单

注意下 cron.WithSeconds() 如果不加的话 这个 cron只支持5个参数,

cron2 := cron.New(cron.WithSeconds()) //创建一个cron实例 
//cron.WithSeconds() 这个参数是开启秒级的数据
_, err := cron2.AddFunc("*/5 * * * * ?", func() {
  //你的业务逻辑
})
cron2.Start()
if err != nil {
   log.Println("write", err)

}

 这个链接有详细的说明

https://www.jianshu.com/p/232348a84601

猜你喜欢

转载自blog.csdn.net/qq_39164154/article/details/124620123