0
点赞
收藏
分享

微信扫一扫

Go整合cron实现定时任务


下载安装:

go get github.com/robfig/cron

v3版本安装(适用于Go 1.11版本及之后的):

go get github.com/robfig/cron/v3@v3.0.0

代码:

package main

import (
"fmt"
"github.com/robfig/cron/v3"
"time"
)

func main() {
methodB()
}

func methodA() {
c := cron.New(cron.WithSeconds()) //精确到秒级,V3版本之后提供的
//定时任务
spec := "*/1 * * * * ?" //cron表达式,每秒一次
c.AddFunc(spec, func() {
fmt.Println("methodA 每秒一次...")
})
c.Start()
select {} //阻塞主线程停止
}

func methodB() {
c := cron.New()
//定时任务
spec := "*/1 * * * * ?" //cron表达式,每秒一次
c.AddFunc(spec, func() {
fmt.Println("methodA 每秒一次...")
time.Sleep(time.Second*5)
c.Stop()//停止任务
})
c.Start()
select {
}
}

func methodC() {
fmt.Println("methodC 定时任务C")
}

func methodE() {
fmt.Println("methodC 定时任务C")
}

func methodD() {
c := cron.New()
//定时任务
spec := "*/1 * * * * ?" //cron表达式,每秒一次
c.AddFunc(spec, methodE)
c.AddFunc(spec, methodC)
c.Start()
select {} //阻塞主线程停止
}

常用的cron字符串:




举报

相关推荐

0 条评论