Home > OS >  Golang Robfig cron AddFunc does not dynamically run the jobs
Golang Robfig cron AddFunc does not dynamically run the jobs

Time:10-13

I am working on a cron jobs service using robfig/cron module. Issue I am facing is it is not able to dynamically run the cron job functions. For example, refer to the code below

    mapp := map[int]string{1: "one", 2: "two", 3: "three"}

    cr := cron.New()


    for integ, spell := range mapp {
        cr.AddFunc("@every 2s", func() { 
          fmt.Println("Running Cron Spell:", spell, "Integer:",integ)})

    }

    cr.Start() 

The output is as below for every 2 seconds

Running Cron Spell: three Integer: 3
Running Cron Spell: three Integer: 3
Running Cron Spell: three Integer: 3

The output is same for all the 3 cron jobs. I was expecting it to give output something like this.

Running Cron Spell: one Integer: 1
Running Cron Spell: two Integer: 2
Running Cron Spell: three Integer: 3

I am not sure whether it is a bug or I am doing it wrong. My goal is to let the cron jobs run dynamically based on configured value. Is there any workaround that I can make it as my desired output?

CodePudding user response:

Reassign the range variables in the loop:

    for integ, spell := range mapp {
        integ, spell := integ, spell
        cr.AddFunc("@every 2s", func() { 
          fmt.Println("Running Cron Spell:", spell, "Integer:",integ)})

    }

The range variable is the same one reutilized on each iteration. If you close around it, the closure (function literal) will see the last value in the iteration.

  • Related