Home >Backend Development >Golang >Why Does My Go Cron Scheduler Print the Last Job\'s Description for All Jobs?

Why Does My Go Cron Scheduler Print the Last Job\'s Description for All Jobs?

DDD
DDDOriginal
2024-11-17 14:10:02232browse

Why Does My Go Cron Scheduler Print the Last Job's Description for All Jobs?

Cannot Assign Variable to Anonymous Function in for Loop: A Closure Pitfall

While studying go-lang, you encountered a problem while developing a task scheduler using the cron library. You observed that the scheduler was printing the description of the last job for all scheduled jobs. This behavior is caused by the use of anonymous functions within the for loop, which leads to closure pitfalls.

In Go, the val variable in a for loop takes on the value of each slice element. When you use closure within the loop, all closures are bound to that same variable. Since the goroutines will likely not execute until after the loop, you end up printing the last element multiple times.

To resolve this issue, you attempted to pass the job as a parameter to the anonymous function. However, the cron library does not accept functions with parameters, as it expects a function type of func().

The recommended solution is to create a new variable for each iteration of the loop. By assigning the current job to a new variable (realJob), you create a new scope for the closure, ensuring that each closure has its own instance of the job variable.

Here's the corrected code:

for _, job := range config.Jobs {
    realJob := job
    c.AddFunc("@every "+realJob.Interval, func() {
        DistributeJob(realJob)
    })
    log.Println("Job " + realJob.Name + " has been scheduled!")
}

By creating a new realJob variable within each loop iteration, you avoid the closure pitfalls and ensure that each scheduled job prints the correct description.

The above is the detailed content of Why Does My Go Cron Scheduler Print the Last Job\'s Description for All Jobs?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn