Files
mayfly-go/server/pkg/scheduler/scheduler.go

67 lines
1.1 KiB
Go
Raw Normal View History

2020-09-01 10:34:11 +08:00
package scheduler
import (
"mayfly-go/pkg/logx"
"sync"
2021-01-08 15:37:32 +08:00
2020-09-01 10:34:11 +08:00
"github.com/robfig/cron/v3"
)
2022-07-24 15:37:13 +08:00
func init() {
Start()
}
var (
cronService = cron.New(cron.WithSeconds())
key2IdMap sync.Map
)
2020-09-01 10:34:11 +08:00
func Start() {
2021-04-16 15:10:07 +08:00
cronService.Start()
2020-09-01 10:34:11 +08:00
}
func Stop() {
2021-04-16 15:10:07 +08:00
cronService.Stop()
}
2025-04-16 12:09:55 +08:00
// Remove 根据任务id移除
2021-04-16 15:10:07 +08:00
func Remove(id cron.EntryID) {
cronService.Remove(id)
2020-09-01 10:34:11 +08:00
}
2025-04-16 12:09:55 +08:00
// RemoveByKey 根据任务key移除
func RemoveByKey(key string) {
2025-04-16 12:09:55 +08:00
logx.Debugf("remove cron func => [key = %s]", key)
id, ok := key2IdMap.Load(key)
if ok {
Remove(id.(cron.EntryID))
key2IdMap.Delete(key)
}
}
2020-09-01 10:34:11 +08:00
func GetCron() *cron.Cron {
2021-04-16 15:10:07 +08:00
return cronService
2020-09-01 10:34:11 +08:00
}
2025-04-16 12:09:55 +08:00
// AddFun 添加任务
func AddFun(spec string, cmd func()) (cron.EntryID, error) {
return cronService.AddFunc(spec, cmd)
2020-09-01 10:34:11 +08:00
}
2025-04-16 12:09:55 +08:00
// AddFunByKey 根据key添加定时任务
func AddFunByKey(key, spec string, cmd func()) error {
logx.Debugf("add cron func => [key = %s]", key)
RemoveByKey(key)
2025-04-16 12:09:55 +08:00
id, err := AddFun(spec, cmd)
if err != nil {
return err
}
key2IdMap.Store(key, id)
return nil
}
func ExistKey(key string) bool {
_, ok := key2IdMap.Load(key)
return ok
}