英文:
Golang Robfig cron AddFunc does not dynamically run the jobs
问题
我正在使用robfig/cron模块开发一个cron作业服务。我遇到的问题是它无法动态运行cron作业函数。例如,参考下面的代码:
mapp := map[int]string{1: "one", 2: "two", 3: "three"}
cr := cron.New()
for integ, spell := range mapp {
cr.AddFunc("@every 2s", func() {
fmt.Println("Running Cron Spell:", spell, "Integer:",integ)})
}
cr.Start()
每2秒的输出如下:
Running Cron Spell: three Integer: 3
Running Cron Spell: three Integer: 3
Running Cron Spell: three Integer: 3
所有3个cron作业的输出都相同。我原本期望输出类似于这样:
Running Cron Spell: one Integer: 1
Running Cron Spell: two Integer: 2
Running Cron Spell: three Integer: 3
我不确定这是一个bug还是我做错了。我的目标是根据配置的值动态运行cron作业。是否有任何解决方法可以得到我期望的输出?
英文:
I am working on a cron jobs service using robfig/cron module. Issue I am facing is it is not able to dynamically run the cron job functions. For example, refer to the code below
mapp := map[int]string{1: "one", 2: "two", 3: "three"}
cr := cron.New()
for integ, spell := range mapp {
cr.AddFunc("@every 2s", func() {
fmt.Println("Running Cron Spell:", spell, "Integer:",integ)})
}
cr.Start()
The output is as below for every 2 seconds
Running Cron Spell: three Integer: 3
Running Cron Spell: three Integer: 3
Running Cron Spell: three Integer: 3
The output is same for all the 3 cron jobs. I was expecting it to give output something like this.
Running Cron Spell: one Integer: 1
Running Cron Spell: two Integer: 2
Running Cron Spell: three Integer: 3
I am not sure whether it is a bug or I am doing it wrong. My goal is to let the cron jobs run dynamically based on configured value. Is there any workaround that I can make it as my desired output?
答案1
得分: 4
重新分配循环中的范围变量:
for integ, spell := range mapp {
integ, spell := integ, spell
cr.AddFunc("@every 2s", func() {
fmt.Println("Running Cron Spell:", spell, "Integer:",integ)})
}
范围变量是在每次迭代中重新利用的相同变量。如果在闭包(函数字面量)中引用它,闭包将看到迭代中的最后一个值。
英文:
Reassign the range variables in the loop:
for integ, spell := range mapp {
integ, spell := integ, spell
cr.AddFunc("@every 2s", func() {
fmt.Println("Running Cron Spell:", spell, "Integer:",integ)})
}
The range variable is the same one reutilized on each iteration. If you close around it, the closure (function literal) will see the last value in the iteration.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论