From e10966b23a5dc2b0fef4357fca26c07496726a1b Mon Sep 17 00:00:00 2001 From: snowlyg <569616226@qq.com> Date: Tue, 28 Jun 2022 11:14:02 +0800 Subject: [PATCH] add do once job function --- server/cron_server/index.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/server/cron_server/index.go b/server/cron_server/index.go index 1693e9f9..233243e6 100644 --- a/server/cron_server/index.go +++ b/server/cron_server/index.go @@ -2,7 +2,9 @@ package cron_server import ( "errors" + "fmt" "sync" + "time" "github.com/robfig/cron/v3" ) @@ -24,3 +26,17 @@ func CronInstance() *cron.Cron { }) return cc } + +// DoOnce run job once time,this job will run after 2 second +func DoOnce(job cron.Job, t ...time.Duration) error { + once := time.Now().Add(2 * time.Second) + if len(t) == 1 { + once = time.Now().Add(t[0] * time.Second) + } + onceSpec := fmt.Sprintf("%d %d %d %d %d %d", once.Second(), once.Minute(), once.Hour(), once.Day(), once.Month(), once.Weekday()) + _, err := CronInstance().AddJob(onceSpec, job) + if err != nil { + return err + } + return nil +}