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

65 lines
1.0 KiB
Go
Raw Normal View History

2020-09-01 10:34:11 +08:00
package scheduler
import (
"mayfly-go/pkg/biz"
"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()
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()
}
// 根据任务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
}
// 根据任务key移除
func RemoveByKey(key string) {
logx.Debugf("移除cron任务 => [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
}
// 添加任务
2020-09-01 10:34:11 +08:00
func AddFun(spec string, cmd func()) cron.EntryID {
2021-04-16 15:10:07 +08:00
id, err := cronService.AddFunc(spec, cmd)
2023-02-20 18:41:45 +08:00
biz.ErrIsNilAppendErr(err, "添加任务失败: %s")
2020-09-01 10:34:11 +08:00
return id
}
// 根据key添加定时任务
func AddFunByKey(key, spec string, cmd func()) {
logx.Debugf("添加cron任务 => [key = %s]", key)
RemoveByKey(key)
key2IdMap.Store(key, AddFun(spec, cmd))
}
func ExistKey(key string) bool {
_, ok := key2IdMap.Load(key)
return ok
}