Home >Backend Development >Golang >How to Fix Closure Issues When Scheduling Jobs in a For Loop?

How to Fix Closure Issues When Scheduling Jobs in a For Loop?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-24 19:25:13762browse

How to Fix Closure Issues When Scheduling Jobs in a For Loop?

Resolving Closure Issues in For Loops: Cannot Assign Variable to Anonymous Func

In the context of creating a task schedular, you encountered an issue where scheduled jobs printed the description of the last iterated job instead of their own. This issue stemmed from using anonymous functions within a for loop.

The challenge arises from the fact that all closures in your loop shared the same variable (in your case, the job variable). As you progressed through the loop, the variable was overwritten with the data from the next job.

To resolve this, you attempted to pass the job variable as an argument to the anonymous function, but you received an error because functions with parameters have a different type than those without parameters.

The recommended solution is to create a new variable (in your case, realJob) for each iteration of the loop to maintain a unique reference to each job. By doing so, you avoid the closure issue and ensure that each scheduled job prints its own correct description.

Here's the revised code:

for _, job := range config.Jobs {
    realJob := job // a new variable each time through the loop
    c.AddFunc("@every "+realJob.Interval, func() {
        DistributeJob(realJob)
    })
    log.Println("Job " + realJob.Name + " has been scheduled!")
}

The above is the detailed content of How to Fix Closure Issues When Scheduling Jobs in a For Loop?. 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