From 432725b80db35f00c08bc5bfe373c1baf123e26d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8D=AF=E8=A6=81=E5=90=83?= <49603204+yaoyaochil@users.noreply.github.com> Date: Wed, 9 Aug 2023 16:17:34 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20timed=5Ftask.go=20?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E4=BA=86=E4=B8=A4=E4=B8=AA=E6=96=B9=E6=B3=95?= =?UTF-8?q?=20(#1504)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add:Timer工具增加AddTaskByFuncWithSeconds与AddTaskByJobWithSeconds方法 Fix:解决添加定时任务没有按时运行问题 --- server/utils/timer/timed_task.go | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/server/utils/timer/timed_task.go b/server/utils/timer/timed_task.go index b0bfb80f..c5c1e4c1 100644 --- a/server/utils/timer/timed_task.go +++ b/server/utils/timer/timed_task.go @@ -35,6 +35,19 @@ func (t *timer) AddTaskByFunc(taskName string, spec string, task func(), option return id, err } +// AddTaskByFuncWithSeconds 通过函数的方法使用WithSeconds添加任务 +func (t *timer) AddTaskByFuncWhithSecond(taskName string, spec string, task func(), option ...cron.Option) (cron.EntryID, error) { + t.Lock() + defer t.Unlock() + option = append(option, cron.WithSeconds()) + if _, ok := t.taskList[taskName]; !ok { + t.taskList[taskName] = cron.New(option...) + } + id, err := t.taskList[taskName].AddFunc(spec, task) + t.taskList[taskName].Start() + return id, err +} + // AddTaskByJob 通过接口的方法添加任务 func (t *timer) AddTaskByJob(taskName string, spec string, job interface{ Run() }, option ...cron.Option) (cron.EntryID, error) { t.Lock() @@ -47,6 +60,19 @@ func (t *timer) AddTaskByJob(taskName string, spec string, job interface{ Run() return id, err } +// AddTaskByJobWithSeconds 通过接口的方法添加任务 +func (t *timer) AddTaskByJobWithSeconds(taskName string, spec string, job interface{ Run() }, option ...cron.Option) (cron.EntryID, error) { + t.Lock() + defer t.Unlock() + option = append(option, cron.WithSeconds()) + if _, ok := t.taskList[taskName]; !ok { + t.taskList[taskName] = cron.New(option...) + } + id, err := t.taskList[taskName].AddJob(spec, job) + t.taskList[taskName].Start() + return id, err +} + // FindCron 获取对应taskName的cron 可能会为空 func (t *timer) FindCron(taskName string) (*cron.Cron, bool) { t.Lock()