前言
go执行定时任务,可以使用robfig/cron/v3
包,robfig/cron/v3 是一个 Golang 的定时任务库,支持 cron 表达式
定时任务使用
参考文档
定时任务参考文档可以参考
arduino
https://pkg.go.dev/github.com/robfig/cron/v3
依赖安装
执行以下命令安装依赖
kotlin
go get github.com/robfig/cron/v3@v3.0.0
cron使用
每分钟执行一次
go
package main
import (
"github.com/robfig/cron/v3"
"log"
"time"
)
func TestCron() {
c := cron.New()
i := 1
_, err := c.AddFunc("* * * * *", func() {
log.Println("数据为: ", i)
i++
})
if err != nil {
return
}
c.Start()
time.Sleep(time.Minute * 5)
}
func main() {
TestCron()
}
输出结果
corn支持秒
精确到秒的 Cron 表达式
Cron v3 版本的表达式从六个参数调整为五个,取消了对秒的默认支持,需要精确到秒的控制可以使用 cron.WithSeconds()
解析器
每秒执行一次
go
package main
import (
"github.com/robfig/cron/v3"
"log"
"time"
)
func TestCron() {
c := cron.New(cron.WithSeconds())
i := 1
_, err := c.AddFunc("*/1 * * * * *", func() {
log.Println("数据为: ", i)
i++
})
if err != nil {
return
}
c.Start()
time.Sleep(time.Minute * 5)
}
func main() {
TestCron()
}
输出结果为
使用@every
每10s执行一次
go
package main
import (
"fmt"
"github.com/robfig/cron/v3"
"time"
)
func TestCron() {
c := cron.New()
c.AddFunc("@every 10s", func() {
fmt.Println("Every 10 Seconds")
})
c.Start()
time.Sleep(time.Minute * 5)
}
func main() {
TestCron()
}
输出结果为
设置时区
scss
package main
import (
"fmt"
"github.com/robfig/cron/v3"
"time"
)
func TestCron() {
//c := cron.New()
// 上海时区早六点
nyc, _ := time.LoadLocation("Asia/Shanghai")
c := cron.New(cron.WithLocation(nyc))
c.AddFunc("@every 10s", func() {
fmt.Println(12)
})
c.Start()
time.Sleep(time.Minute * 5)
}
func main() {
TestCron()
}
AddJob使用
go
package main
import (
"github.com/robfig/cron/v3"
"log"
"time"
)
func TestCron() {
c := cron.New(cron.WithSeconds())
// 上海时区早六点
_, err := c.AddJob("*/5 * * * * *", Hello{})
if err != nil {
return
}
c.Start()
time.Sleep(time.Minute * 5)
}
type Hello struct {
}
func (t Hello) Run() {
log.Println("hello world")
}
func main() {
TestCron()
}
输出结果为
终止任务
go
package main
import (
"github.com/robfig/cron/v3"
"log"
"time"
)
func TestCron() {
c := cron.New(cron.WithSeconds())
// 上海时区早六点
_, err := c.AddJob("*/2 * * * * *", Hello{})
if err != nil {
return
}
c.Start()
go func() {
time.Sleep(5 * time.Second)
log.Println("==============终止任务")
c.Stop()
}()
time.Sleep(time.Minute * 5)
}
type Hello struct {
}
func (t Hello) Run() {
log.Println("hello world")
}
func main() {
TestCron()
}
输出结果为
总结
cron
则提供了更强大的定时任务调度功能,适用于复杂场景。根据实际需求选择合适的方法,可以方便地实现定时任务的开发