gocron创建多个任务实例

编程入门 行业动态 更新时间:2024-10-25 12:23:21
本文介绍了gocron创建多个任务实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在使用这个包的脚本中遇到问题:

github/jasonlvhit/gocron

在我找不到错误之后,我写了这个小小的测试脚本,导致执行了两倍的cronjobs按照预期:

func main(){ for i:= 0;我< 3; i ++ { channel:= make(chan string) go taskCron(channel,i)} time.Sleep(time.Second * 5) gocron.Clear() fmt.Println(stop this shit)} func任务(i int){ fmt.Println(仍然在运行......,i)} func taskCron(channel chan string,i int){ gocron.Every(4).Seconds().Do任务,i) <-gocron.Start()}

运行它给了我这个输出:

- ▶运行* .go 仍在运行... 0 仍在运行... 0 仍在运行中... 1 仍在运行中... 1 仍在运行中... 2 仍在运行... 2 仍在运行... 0 仍在运行... 1 仍在运行... 2 停止此 有谁知道如何创建动态数量的gocron作业而不复制它们?

感谢:)

解决方案

确定显然

< -gocron.Start()

将启动已经启动的作业,以便解决我的问题,我必须将脚本更改为:

func main(){ for i:= 0;我< 3; i ++ { taskCron(i)} channel2:= make(chan int) go startCron(channel2) time.Sleep(time。秒* 5) gocron.Clear() fmt.Println(stop this)} func任务(i int){ fmt.Println(仍在运行...,i)} func taskCron(i int){ gocron.Every(4).Seconds()。 (任务,i)} func startCron(channel chan int){ <-gocron.Start()}

我希望这可以帮助任何有同样问题的人!

I had a problem in a script using this package:

"github/jasonlvhit/gocron"

I wrote this little testscript after I couldn't find a mistake and it resulted that there were twice as many cronjobs executed as intended:

func main() { for i := 0; i < 3; i++ { channel := make(chan string) go taskCron(channel, i) } time.Sleep(time.Second * 5) gocron.Clear() fmt.Println("stop this shit") } func task(i int) { fmt.Println("still running...", i) } func taskCron(channel chan string, i int) { gocron.Every(4).Seconds().Do(task, i) <-gocron.Start() }

running it gave me this output:

——▶go run *.go still running... 0 still running... 0 still running... 1 still running... 1 still running... 2 still running... 2 still running... 0 still running... 1 still running... 2 stop this

Does anyone know how I can create a dynamic amount of gocron jobs without duplicating them?

Thanks :)

解决方案

Ok apparently

<-gocron.Start()

will start jobs that were already startet again so to fix my issue, I had to change the script to this:

func main() { for i := 0; i < 3; i++ { taskCron(i) } channel2 := make(chan int) go startCron(channel2) time.Sleep(time.Second * 5) gocron.Clear() fmt.Println("stop this") } func task(i int) { fmt.Println("still running...", i) } func taskCron(i int) { gocron.Every(4).Seconds().Do(task, i) } func startCron(channel chan int) { <-gocron.Start() }

I hope this helps anybody who had the same Problem!

更多推荐

gocron创建多个任务实例

本文发布于:2023-11-23 21:09:45,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   实例   gocron

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!