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

Issue


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
}

output got by the above program:

acessesing gateway 13

acessesing gateway 13

acessesing gateway 13

acessesing gateway 13

acessesing gateway 13

acessesing gateway 13

acessesing gateway 13

acessesing gateway 13

acessesing gateway 13

acessesing gateway 13

acessesing gateway 13

acessesing gateway 13

acessesing gateway 13

acessesing gateway 13

I like run the same function with different input

Expected output for every 30s

acessesing gateway 1

acessesing gateway 2

acessesing gateway 3

acessesing gateway 4

acessesing gateway 5

acessesing gateway 6

acessesing gateway 7

acessesing gateway 8

acessesing gateway 9

acessesing gateway 10

Solution

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

Answered By – eugenioy

Answer Checked By – Clifford M. (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.