定时任务
# 创建一个定时任务步聚如下:
- 创建定义cron
// 代码见 modules\system\worker\cron\test_cron.go 新文件建在同一目录
package cron
import (
"devinggo/modules/system/pkg/worker/cron"
glob2 "devinggo/modules/system/pkg/worker/glob"
"devinggo/modules/system/pkg/worker/task"
"devinggo/modules/system/worker/consts"
"context"
"github.com/gogf/gf/v2/encoding/gjson"
"github.com/gogf/gf/v2/frame/g"
"github.com/hibiken/asynq"
)
# 初始化一个cron
var testCron = &ctestCron{
Type: consts.TEST_CRON, # 任务名称 ,重要
Description: "This is a test cron", # 任务描述
Payload: &glob2.Payload{},
}
type ctestCron struct {
Type string
Description string
Payload *glob2.Payload
}
type TestCronData struct { // 传输的数据格式,重要
Name string `json:"name"`
}
func init() {
cron.Register(testCron)
}
func (s *ctestCron) GetType() string {
return s.Type
}
func (s *ctestCron) GetCronTask() *asynq.Task {
return task.GetTask(s)
}
func (s *ctestCron) GetPayload() *glob2.Payload {
return s.Payload
}
func (s *ctestCron) GetDescription() string {
return s.Description
}
func (s *ctestCron) SetParams(ctx context.Context, params *gjson.Json) {
if g.IsEmpty(params) {
return
}
data := new(TestCronData)
if err := params.Scan(data); err != nil {
glob2.WithWorkLog().Errorf(ctx, "[%s] cron SetParams failed:%v", s.Type, err)
return
}
s.Payload.Data = data
}
- 绑定执行定时任务的worker
# 见 modules\system\worker\server\test_cron_worker.go 新文件建在同一目录
package server
import (
glob2 "devinggo/modules/system/pkg/worker/glob"
"devinggo/modules/system/pkg/worker/server"
"devinggo/modules/system/worker/consts"
"devinggo/modules/system/worker/cron"
"context"
"github.com/hibiken/asynq"
)
var testCronWorker = &ctestCronWorker{
Type: consts.TEST_CRON, #任务名称,同上面定义相同,重要
}
type ctestCronWorker struct {
Type string
}
func init() {
server.Register(testCronWorker)
}
func (s *ctestCronWorker) GetType() string {
return s.Type
}
// Execute 执行任务
func (s *ctestCronWorker) Execute(ctx context.Context, t *asynq.Task) (err error) {
data, err := glob2.GetParamters[cron.TestCronData](ctx, t)
if err != nil {
return err
}
glob2.WithWorkLog().Infof(ctx, `jsonData:%+v`, data)
// todo 执行代码,在这里添加
return
}
- 重启服务,登录后台,定时任务管理页面添加
job任务
上次更新: 2025/01/08, 17:33:46