I'm studying go-lang by developing a task schedular. The cron library I use accepts a cron expression and a func as parameters to add a scheduler.
c.AddFunc("0 30 * * * *", func() { fmt.Println("Every hour on the half hour") })
The schedular I am developing schedules jobs according to a yaml file. So I iterate the jobs to add schedulars like this:
type Job struct {
Name string
Interval string
}
func DistributeJob(job Job) {
log.Println("running", job, job.Interval)
}
func main() {
//load config from yaml
c := cron.New()
for _, job := range config.Jobs {
c.AddFunc("@every "+job.Interval, func() {
DistributeJob(job)
})
log.Println("Job " + job.Name + " has been scheduled!")
}
c.Start()
select {}
}
All jobs are scheduled on their intervals but it turns out that they're printing the last job's description. For example, if I schedule two jobs, the first interval on 3min and the latter interval on 1min. The console prints:
12:01: Running latter 1min 12:02: Running latter 1min 12:03: Running latter 1min 12:03: Running latter 1min//this one should be the first job
I think the problem is at
func() {
DistributeJob(job)
})
It seems it only takes the last job but I can't figure out why. I tried using
c.AddFunc("@every "+job.Interval, func(job JobType) {
DistributeJob(job)
}(job))
but it fails due to cannot used as value