Skip to content

Commit 432725b

Browse files
authored
更新 timed_task.go 增加了两个方法 (#1504)
Add:Timer工具增加AddTaskByFuncWithSeconds与AddTaskByJobWithSeconds方法 Fix:解决添加定时任务没有按时运行问题
1 parent 91c2909 commit 432725b

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

server/utils/timer/timed_task.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,19 @@ func (t *timer) AddTaskByFunc(taskName string, spec string, task func(), option
3535
return id, err
3636
}
3737

38+
// AddTaskByFuncWithSeconds 通过函数的方法使用WithSeconds添加任务
39+
func (t *timer) AddTaskByFuncWhithSecond(taskName string, spec string, task func(), option ...cron.Option) (cron.EntryID, error) {
40+
t.Lock()
41+
defer t.Unlock()
42+
option = append(option, cron.WithSeconds())
43+
if _, ok := t.taskList[taskName]; !ok {
44+
t.taskList[taskName] = cron.New(option...)
45+
}
46+
id, err := t.taskList[taskName].AddFunc(spec, task)
47+
t.taskList[taskName].Start()
48+
return id, err
49+
}
50+
3851
// AddTaskByJob 通过接口的方法添加任务
3952
func (t *timer) AddTaskByJob(taskName string, spec string, job interface{ Run() }, option ...cron.Option) (cron.EntryID, error) {
4053
t.Lock()
@@ -47,6 +60,19 @@ func (t *timer) AddTaskByJob(taskName string, spec string, job interface{ Run()
4760
return id, err
4861
}
4962

63+
// AddTaskByJobWithSeconds 通过接口的方法添加任务
64+
func (t *timer) AddTaskByJobWithSeconds(taskName string, spec string, job interface{ Run() }, option ...cron.Option) (cron.EntryID, error) {
65+
t.Lock()
66+
defer t.Unlock()
67+
option = append(option, cron.WithSeconds())
68+
if _, ok := t.taskList[taskName]; !ok {
69+
t.taskList[taskName] = cron.New(option...)
70+
}
71+
id, err := t.taskList[taskName].AddJob(spec, job)
72+
t.taskList[taskName].Start()
73+
return id, err
74+
}
75+
5076
// FindCron 获取对应taskName的cron 可能会为空
5177
func (t *timer) FindCron(taskName string) (*cron.Cron, bool) {
5278
t.Lock()

0 commit comments

Comments
 (0)