gocron/utils/cron_task.go

90 lines
1.7 KiB
Go
Raw Normal View History

2017-03-10 09:08:51 +00:00
package utils
import (
"github.com/robfig/cron"
"errors"
2017-03-10 10:08:45 +00:00
"scheduler/utils/app"
2017-03-13 09:21:21 +00:00
"sync"
2017-03-10 09:08:51 +00:00
)
2017-03-10 10:08:45 +00:00
var DefaultCronTask CronTask;
2017-03-10 09:08:51 +00:00
type CronTask struct {
2017-03-13 09:21:21 +00:00
sync.RWMutex
2017-03-10 09:08:51 +00:00
tasks map[string]*cron.Cron
}
2017-03-10 10:08:45 +00:00
func init() {
if app.Installed {
DefaultCronTask = CronTask{
2017-03-13 09:21:21 +00:00
sync.RWMutex{},
2017-03-10 10:08:45 +00:00
make(map[string]*cron.Cron),
}
}
}
2017-03-10 09:08:51 +00:00
// 新增定时任务,如果name存在则添加失败
func(cronTask *CronTask) Add(name string, spec string, cmd func() ) error {
if name == "" || spec == "" || cmd == nil {
return errors.New("参数不完整")
}
if cronTask.IsExist(name) {
return errors.New("任务已存在")
}
2017-03-13 09:21:21 +00:00
cronTask.Lock()
defer cronTask.Unlock()
2017-03-10 09:08:51 +00:00
cronTask.tasks[name] = cron.New()
err := cronTask.tasks[name].AddFunc(spec, cmd)
return err
}
// 任务不存在则新增,任务已存在则替换任务
func(cronTask *CronTask) addOrReplace(name string, spec string, cmd func() ) error {
if cronTask.IsExist(name) {
cronTask.Delete(name)
}
return cronTask.Add(name, spec, cmd)
}
// 判断任务是否存在
func(cronTask *CronTask) IsExist(name string) bool {
2017-03-13 09:21:21 +00:00
cronTask.RLock()
defer cronTask.RUnlock()
2017-03-10 09:08:51 +00:00
_, ok := cronTask.tasks[name]
return ok
}
// 启动任务
func(cronTask *CronTask) Start(name string) {
if cronTask.IsExist(name) {
cronTask.tasks[name].Start()
}
}
// 停止任务
func(cronTask *CronTask) Stop(name string) {
if cronTask.IsExist(name) {
cronTask.tasks[name].Stop()
}
}
// 删除任务
func(cronTask *CronTask) Delete(name string) {
cronTask.Stop(name)
2017-03-13 09:21:21 +00:00
cronTask.Lock()
defer cronTask.Unlock()
2017-03-10 09:08:51 +00:00
delete(cronTask.tasks, name)
}
// 运行所有任务
func(cronTask *CronTask) run() {
for _, cron := range cronTask.tasks {
2017-03-13 09:21:21 +00:00
// cron内部有开启goroutine,此处不用新建goroutine
2017-03-10 09:08:51 +00:00
cron.Start()
}
}