2
通过 gf init scratches 创建项目后,新增 cron.go 文件如下:
package cron
import (
"context"
"time"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gcron"
"github.com/gogf/gf/v2/os/gctx"
)
func init() {
if _, err := gcron.AddSingleton(gctx.New(), "0 9 11 * * *", func(ctx context.Context) {
g.Log().Print(ctx, "task started")
time.Sleep(2 * time.Second)
g.Log().Print(ctx, "task ended")
}, "Cron Task"); err != nil {
g.Log("Daily task error", err.Error())
}
}
在 main.go 中引用:
package main
import (
_ "Scratches/cron"
"Scratches/internal/cmd"
_ "Scratches/internal/packed"
"github.com/gogf/gf/v2/os/gctx"
)
func main() {
cmd.Main.Run(gctx.New())
}
执行 go run main.go 后,可以发现在 11 点 9 分开始、结束时,分别执行一次计划任务,类似:
2022-12-06 11:09:00.942 {485e1eac75152e17ce320535bd303269} task started
2022-12-06 11:09:02.942 {485e1eac75152e17ce320535bd303269} task ended
2022-12-06 11:09:59.942 {485e1eac75152e17ce320535bd303269} task started
2022-12-06 11:10:01.943 {485e1eac75152e17ce320535bd303269} task ended
重复执行两次
在指定时间点只执行一次