package crontab import ( "encoding/json" "fmt" "sync" "tools/entity" "tools/logic/cutil" "tools/logic/orm" "github.com/robfig/cron/v3" "github.com/spf13/cast" ) type Crontab struct { sync.Mutex TaskId int64 `json:"task_id"` Cron string `json:"cron"` Url string `json:"url"` Name string `json:"name"` Desc string `json:"desc"` Author string `json:"author"` Status int32 `json:"status"` } var taskKey = "h:gm:crontab:list" var commander *cron.Cron var taskIdPool map[cron.EntryID]*Crontab //func init() { // orm.RegisterSupervisor[*Crontab]() // taskIdPool = make(map[cron.EntryID]*Crontab) // var nyc, _ = time.LoadLocation("Local") // loc := cron.WithLocation(nyc) // commander = cron.New(loc) //} func Start() { load() tasks := orm.GetAll[*Crontab]() start(tasks) } func ReStart() { commander.Stop() for id, _ := range taskIdPool { commander.Remove(id) delete(taskIdPool, id) } Start() } func add(task *Crontab) { orm.Register[*Crontab](task) ReStart() } func (task *Crontab) Working() { if task.Status == 1 { host := entity.GetConf().CronHost response, err := cutil.Get(host + task.Url) if err != nil { return } fmt.Println(response) } } func (task *Crontab) Id() int64 { return task.TaskId } func (task *Crontab) Commit() { redis := entity.GetRedis() redis.HSet(taskKey, cast.ToString(task.TaskId), task.ToString()) } func (task *Crontab) delete() { task.Status = 0 err := orm.Delete[*Crontab](task.TaskId, func(t *Crontab) { redis := entity.GetRedis() redis.HDel(taskKey, cast.ToString(t.TaskId)) }) if err != nil { return } } func (task *Crontab) open() { task.Status = 1 } func (task *Crontab) Stop() { task.Status = 0 } func (task *Crontab) ToString() string { js, err := json.Marshal(task) if err != nil { return "" } return string(js) } func load() { redis := entity.GetRedis() list := redis.HGetAll(taskKey) values := list.Val() for _, val := range values { task := &Crontab{} err := json.Unmarshal([]byte(val), task) if err != nil { panic("marshal crontab task error") } orm.Register[*Crontab](task) } } func start(tasks map[int64]*Crontab) map[cron.EntryID]*Crontab { for _, task := range tasks { fmt.Println("启动任务:" + task.Cron + " 名称:" + task.Name) id, err := commander.AddFunc(task.Cron, task.Working) if err != nil { fmt.Println("启动任务失败" + task.Cron + " 名称:" + task.Name) commander.Stop() return nil } taskIdPool[id] = task } commander.Start() return taskIdPool }