如何使用一个函数和不同的参数创建Cron任务?

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

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 {}

huangapple
  • 本文由 发表于 2021年8月24日 10:27:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/68901064.html
匿名

发表评论

匿名网友

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

确定