Golang Robfig cron AddFunc不动态运行作业



我正在使用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作业基于配置值动态运行。有没有什么方法可以使它成为我想要的输出?

重新赋值循环中的范围变量:

for integ, spell := range mapp {
integ, spell := integ, spell
cr.AddFunc("@every 2s", func() { 
fmt.Println("Running Cron Spell:", spell, "Integer:",integ)})
}

range变量是在每次迭代中重用的同一个变量。如果把它括起来,闭包(函数字面量)将看到迭代中的最后一个值。