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