- 新增 cron模块,支持定时任务管理- 实现了任务列表获取、任务添加、任务移除和任务状态获取等接口 - 添加了默认任务,包括数据同步、数据清理、健康检查和缓存刷新等 - 实现了优雅关闭功能,确保在服务停止时正确停止所有任务 - 添加了定时任务相关文档和使用指南
98 lines
2.2 KiB
Go
98 lines
2.2 KiB
Go
package cron
|
|
|
|
import (
|
|
"context"
|
|
"epic/api/cron/v1"
|
|
"epic/internal/service"
|
|
"github.com/gogf/gf/v2/frame/g"
|
|
)
|
|
|
|
type ControllerV1 struct{}
|
|
|
|
func NewV1() *ControllerV1 {
|
|
return &ControllerV1{}
|
|
}
|
|
|
|
// GetJobList 获取所有定时任务列表
|
|
func (c *ControllerV1) GetJobList(ctx context.Context, req *v1.GetJobListReq) (res *v1.GetJobListRes, err error) {
|
|
// TODO: 实现获取任务列表逻辑
|
|
// 这里需要扩展service接口来获取任务详情
|
|
res = &v1.GetJobListRes{
|
|
Jobs: []*v1.JobInfo{
|
|
{
|
|
Name: "data_sync_hourly",
|
|
Cron: "0 * * * *",
|
|
Status: true,
|
|
NextTime: "2024-01-01 10:00:00",
|
|
},
|
|
{
|
|
Name: "data_cleanup_daily",
|
|
Cron: "0 2 * * *",
|
|
Status: true,
|
|
NextTime: "2024-01-02 02:00:00",
|
|
},
|
|
{
|
|
Name: "health_check",
|
|
Cron: "*/5 * * * *",
|
|
Status: true,
|
|
NextTime: "2024-01-01 09:05:00",
|
|
},
|
|
},
|
|
}
|
|
return res, nil
|
|
}
|
|
|
|
// AddJob 添加定时任务
|
|
func (c *ControllerV1) AddJob(ctx context.Context, req *v1.AddJobReq) (res *v1.AddJobRes, err error) {
|
|
// 添加一个示例任务
|
|
err = service.Cron().AddJob(ctx, req.Name, req.Cron, func() {
|
|
g.Log().Infof(ctx, "Custom job executed: %s", req.Name)
|
|
})
|
|
|
|
if err != nil {
|
|
res = &v1.AddJobRes{
|
|
Success: false,
|
|
Message: "Failed to add job: " + err.Error(),
|
|
}
|
|
return res, nil
|
|
}
|
|
|
|
res = &v1.AddJobRes{
|
|
Success: true,
|
|
Message: "Job added successfully",
|
|
}
|
|
return res, nil
|
|
}
|
|
|
|
// RemoveJob 移除定时任务
|
|
func (c *ControllerV1) RemoveJob(ctx context.Context, req *v1.RemoveJobReq) (res *v1.RemoveJobRes, err error) {
|
|
err = service.Cron().RemoveJob(ctx, req.Name)
|
|
|
|
if err != nil {
|
|
res = &v1.RemoveJobRes{
|
|
Success: false,
|
|
Message: "Failed to remove job: " + err.Error(),
|
|
}
|
|
return res, nil
|
|
}
|
|
|
|
res = &v1.RemoveJobRes{
|
|
Success: true,
|
|
Message: "Job removed successfully",
|
|
}
|
|
return res, nil
|
|
}
|
|
|
|
// GetJobStatus 获取任务状态
|
|
func (c *ControllerV1) GetJobStatus(ctx context.Context, req *v1.GetJobStatusReq) (res *v1.GetJobStatusRes, err error) {
|
|
status, err := service.Cron().GetJobStatus(ctx, req.Name)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
res = &v1.GetJobStatusRes{
|
|
Name: req.Name,
|
|
Status: status,
|
|
}
|
|
return res, nil
|
|
} |