为了账号安全,请及时绑定邮箱和手机立即绑定

戈朗·罗布菲格·克朗·阿德芬克不动态运行作业

戈朗·罗布菲格·克朗·阿德芬克不动态运行作业

Go
慕哥9229398 2022-10-04 19:53:22
我正在使用罗布菲格/克隆模块进行克隆工作服务。我面临的问题是它无法动态运行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: 3Running Cron Spell: three Integer: 3Running Cron Spell: three Integer: 3所有 3 个 cron 作业的输出都相同。我期望它能给出这样的东西。Running Cron Spell: one Integer: 1Running Cron Spell: two Integer: 2Running Cron Spell: three Integer: 3我不确定这是一个错误还是我做错了。我的目标是让 cron 作业根据配置的值动态运行。是否有任何解决方法可以使其成为所需的输出?
查看完整描述

1 回答

?
守着一只汪

TA贡献1872条经验 获得超4个赞

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


    for integ, spell := range mapp {

        integ, spell := integ, spell

        cr.AddFunc("@every 2s", func() { 

          fmt.Println("Running Cron Spell:", spell, "Integer:",integ)})


    }

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


查看完整回答
反对 回复 2022-10-04
  • 1 回答
  • 0 关注
  • 126 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号