Gần dây mình có tình viết 1 scheduler bằng Golang.
và mình định sử dụng
gopkg.in/robfig/cron.v3
import (
"fmt"
"gopkg.in/robfig/cron.v3"
)
func test(x int) {
fmt.Println("acessesing device", x)
}
func main() {
c := cron.New()
x := make(chan bool)
devices := [10]int{1,2,3,4,5,6,7,8,9,10}
for _, va := range devices {
c.AddFunc("@every 30s", func() { test(va) })
}
c.Start()
<-x
}
khi đó thì bạn sẽ thấy là dụ sài vòng for nhưng kết quả điều giống nhau.

Nhưng mình mong muốn là như thế này:

Vậy fix sao:
Problem in your code is equivalent to the one described here:
https://github.com/golang/go/wiki/CommonMistakes#using-goroutines-on-loop-iterator-variables
To fix it:
for _, va := range devices {
va := va // create a new "va" variable on each iteration
c.AddFunc("@every 30s", func() { test(va) })
}