【问题标题】:Golang Robfig cron AddFunc does not dynamically run the jobsGolang Robfig cron AddFunc 不会动态运行作业
【发布时间】:2021-12-01 00:09:07
【问题描述】:

我正在使用 robfig/cron 模块开发 cron 作业服务。我面临的问题是它无法动态运行 cron 作业功能。例如,参考下面的代码

    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() 

每2秒输出如下

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

所有 3 个 cron 作业的输出都是相同的。我期待它会给出这样的输出。

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

我不确定这是一个错误还是我做错了。我的目标是让 cron 作业根据配置的值动态运行。有什么解决方法可以让它成为我想要的输出吗?

【问题讨论】:

    标签: go cron scheduled-tasks quartz-scheduler goland


    【解决方案1】:

    在循环中重新分配范围变量:

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

    范围变量与每次迭代中重复使用的变量相同。如果你关闭它,闭包(函数字面量)将看到迭代中的最后一个值。

    【讨论】:

      猜你喜欢
      • 2021-09-21
      • 2013-01-10
      • 2013-07-02
      • 2021-03-27
      • 2016-06-13
      • 1970-01-01
      • 2011-05-10
      相关资源
      最近更新 更多