When using go-cron to work, multiple services are started at the same time, and multiple cron tasks will be executed at the same time?

huangapple go评论93阅读模式
英文:

When using go-cron to work, multiple services are started at the same time, and multiple cron tasks will be executed at the same time?

问题

当使用go-cron工作时,多个服务会同时启动,并且多个cron任务将同时执行。有什么方法可以确保cron任务只执行一次?

我的cron表达式是[0 2 */1 * *]。

英文:

When using go-cron to work, multiple services are started at the same time, and multiple cron tasks will be executed at the same time? What can be done to ensure that the cron task is only executed once?

my cron expression is [0 2 */1 * *]

答案1

得分: 3

你可以配置SingletonMode来防止新的任务在前一个任务尚未完成时启动:

s := gocron.NewScheduler(time.UTC)
_, _ = s.Every(1).Second().SingletonMode().Do(task)

或者启用SingletonModeAll来防止新的任务在特定任务的前一个实例尚未完成时启动:

s := gocron.NewScheduler(time.UTC)
s.SingletonModeAll()

_, _ = s.Every(1).Second().Do(task)
英文:

You can configure the SingletonMode for your task to prevents a new job from starting if the prior job has not yet completed:

	s := gocron.NewScheduler(time.UTC)
	_, _ = s.Every(1).Second().SingletonMode().Do(task)

https://pkg.go.dev/github.com/go-co-op/gocron#Scheduler.SingletonMode

Or enable the SingletonModeAll to prevent new jobs from starting if the prior instance of the particular job has not yet completed:

	s := gocron.NewScheduler(time.UTC)
	s.SingletonModeAll()

	_, _ = s.Every(1).Second().Do(task)

https://pkg.go.dev/github.com/go-co-op/gocron#Scheduler.SingletonModeAll

huangapple
  • 本文由 发表于 2022年12月29日 18:00:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/74949663.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定