如何通过遍历列表来创建多个 CRON 函数

how do I create multiple CRON function by looping through a list


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
}

上述程序得到的输出:

正在访问网关 13

正在访问网关 13

正在访问网关 13

正在访问网关 13

正在访问网关 13

正在访问网关 13

正在访问网关 13

正在访问网关 13

正在访问网关 13

正在访问网关 13

正在访问网关 13

正在访问网关 13

正在访问网关 13

正在访问网关 13

我喜欢运行不同输入的相同功能

每 30 秒的预期输出

正在访问网关 1

正在访问网关 2

正在访问网关 3

正在访问网关 4

正在访问网关 5

正在访问网关 6

正在访问网关 7

正在访问网关 8

正在访问网关 9

正在访问网关 10

您的代码中的问题等同于此处描述的问题:

https://github.com/golang/go/wiki/CommonMistakes#using-goroutines-on-loop-iterator-variables

修复它:

for _, va := range devices {
    va := va // create a new "va" variable on each iteration
    c.AddFunc("@every 30s", func() { test(va) })
}