Files
web_template/internal/task/task.go
2026-07-10 10:06:54 +00:00

54 lines
1.4 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package task
import (
"log"
"github.com/robfig/cron/v3"
)
// Scheduler 定时任务调度器
type Scheduler struct {
cron *cron.Cron
}
// New 创建定时任务调度器
func New() *Scheduler {
return &Scheduler{cron: cron.New(cron.WithSeconds())}
}
// Start 启动定时任务调度器
func (s *Scheduler) Start() {
s.cron.Start()
log.Println("定时任务调度器已启动")
}
// Stop 停止定时任务调度器
func (s *Scheduler) Stop() {
s.cron.Stop()
log.Println("定时任务调度器已停止")
}
// AddFunc 添加定时任务
// spec 为 6 字段 cron 表达式(秒 分 时 日 月 周),cmd 为执行函数
func (s *Scheduler) AddFunc(name, spec string, cmd func()) error {
_, err := s.cron.AddFunc(spec, func() {
log.Printf("定时任务 [%s] 开始执行", name)
cmd()
log.Printf("定时任务 [%s] 执行完成", name)
})
if err != nil {
return err
}
log.Printf("已注册定时任务 [%s]: %s", name, spec)
return nil
}
// RegisterDefaults 注册默认的示例定时任务(扩展位)
// 实际项目中在此添加:订单自动完成、超时退款、优惠券过期、内容审核、账号过期检查等
func (s *Scheduler) RegisterDefaults() {
// 示例:每天凌晨 1 点执行数据清理
_ = s.AddFunc("数据清理示例", "0 0 1 * * *", func() {
log.Println("执行数据清理(示例任务,请按需替换为实际业务)")
})
}