英文:
How to create Cron tasks by one single func with diffenent Parameters?
问题
c := cron.New()
task := inittask()
for _, ta := range task {
c.AddFunc("*/10 * * * * *", func() {getdata(ta, DBS, DBT)})
}
c.Start()
select {}
不起作用,只有第一个或最后一个参数起作用。
英文:
c := cron.New()
task := inittask()
for _, ta := range task {
c.AddFunc("*/10 * * * * *", func() {getdata(ta, DBS, DBT)})
}
c.Start()
select {}
Not working, only the first or the last parameter works.
答案1
得分: 0
_, v := range
循环在每次迭代中分配一个 v
变量,然后在每次迭代中重复使用它。
当你在这样的循环中使用闭包时,你捕获的是这个被重复使用的变量,这导致每个闭包引用相同的内存地址,因此,当循环结束时,每个闭包将具有最后一次迭代的数据。
https://golang.org/doc/faq#closures_and_goroutines
c := cron.New()
task := inittask()
for _, ta := range task {
ta := ta // 复制 ta
c.AddFunc("*/10 * * * * *", func() {getdata(ta, DBS, DBT)})
}
c.Start()
select {}
或者,你也可以通过以下方式解决这个问题:
c := cron.New()
task := inittask()
for i := range task {
c.AddFunc("*/10 * * * * *", func() {getdata(task[i], DBS, DBT)})
}
c.Start()
select {}
英文:
The _, v := range
loop allocates one v
variable and then re-uses it in each iteration.
And when you use closures within such a loop you are capturing that re-used variable which causes each closure to refer to the same memory address and, therefore, when the loop exits, each closure will have the data of the last iteration.
https://golang.org/doc/faq#closures_and_goroutines
c := cron.New()
task := inittask()
for _, ta := range task {
ta := ta // copy ta
c.AddFunc("*/10 * * * * *", func() {getdata(ta, DBS, DBT)})
}
c.Start()
select {}
Alternatively, you can also get around the problem this way:
c := cron.New()
task := inittask()
for i := range task {
c.AddFunc("*/10 * * * * *", func() {getdata(task[i], DBS, DBT)})
}
c.Start()
select {}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论