我正在使用羅布菲格/克隆模塊進(jìn)行克隆工作服務(wù)。我面臨的問題是它無法動態(tài)運(yùn)行cron作業(yè)功能。例如,請參閱下面的代碼 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 作業(yè)的輸出都相同。我期望它能給出這樣的東西。Running Cron Spell: one Integer: 1Running Cron Spell: two Integer: 2Running Cron Spell: three Integer: 3我不確定這是一個錯誤還是我做錯了。我的目標(biāo)是讓 cron 作業(yè)根據(jù)配置的值動態(tài)運(yùn)行。是否有任何解決方法可以使其成為所需的輸出?
1 回答
守著一只汪
TA貢獻(xiàn)1872條經(jīng)驗(yàn) 獲得超4個贊
在循環(huán)中重新分配范圍變量:
for integ, spell := range mapp {
integ, spell := integ, spell
cr.AddFunc("@every 2s", func() {
fmt.Println("Running Cron Spell:", spell, "Integer:",integ)})
}
范圍變量與每次迭代時重復(fù)使用的變量相同。如果將其關(guān)閉,則閉包(函數(shù)文本)將看到迭代中的最后一個值。
- 1 回答
- 0 關(guān)注
- 99 瀏覽
添加回答
舉報(bào)
0/150
提交
取消
