Multiple go cron jobs on same function with different parameters

Hi,

I am new to golang. I am trying to write a gocron job which runs every 2 minutes. A separate function is creating new instance of this cron job based on some event. So there will be multiple cron jobs running, executing same function but different arguments .

The issue is whenever new instance is of this cron job is created, the arguments values are being overwritten and all cron jobs are running with the latest argument passed from

func StatusRoutine( ) {
	//based on some event
	arg := "someNewvalue"
	go StartCron(arg)

}
func StartCron(arg string) {
	gocron.Every(2).Minutes().Do(someFunction, arg)

	<-gocron.Start()

}

func someFunction (arg string){

//do something
}

How to make each instance cron job run based on the original arguments?

Advance thanks,

How does this happen? As your code is right now, arg will never change and go StartCron(arg) will always have identical values.

How is the new value of arg assigned?

Hi lutzhorn,

New value for “arg” is actually being passed to StatusRoutine( ) at runtime based on some event.

you can think it as

func StatusRoutine(arg string ) {

go StartCron(arg)

}
The calling function of StatusRoutine is passing new “arg” values every time, e.g. A new user is accessing the application and the “arg” is the email id of user.

Consider this:

package main

import (
	"fmt"
	"math/rand"

	"os"

	"github.com/jasonlvhit/gocron"
)

func main() {
	statusRoutine("foo")
	statusRoutine("bar")
	statusRoutine("baz")

	ch := make(chan string)
	<-ch
}

func statusRoutine(arg string) {
	go startCron(arg)
}

func startCron(arg string) {
	i := rand.Int()
	gocron.Every(3).Seconds().Do(someFunction, arg, i)
	<-gocron.Start()
}

func someFunction(arg string, i int) {
	fmt.Fprintf(os.Stdout, "[%d] %s\n", i, arg)
}

The number i randomly set for each call to someFunction is always associated with the value of arg passed. arg is never overwritten.

Are you sure that the argument of one call to startCron is changed?

Maybe it is a bad idea to call gocron.Start() more than once.

Thanks lutzhorn!

I was missing pushing to channel. It worked .

Thanks again

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.