duanpanbo9476 2019-07-18 13:04
浏览 78
已采纳

如何通过遍历列表创建多个CRON函数


import (
    "fmt"

    "gopkg.in/robfig/cron.v3"
)

func test(x int) {
    fmt.Println("acessesing device", x)
}
func main() {
    c := cron.New()
    x := make(chan bool)
    devices := [10]int{1,2,3,4,5,6,7,8,9,10}
    for _, va := range devices {
        c.AddFunc("@every 30s", func() { test(va) })
    }

    c.Start()
    <-x
}

output got by the above program:

acessesing gateway 13

acessesing gateway 13

acessesing gateway 13

acessesing gateway 13

acessesing gateway 13

acessesing gateway 13

acessesing gateway 13

acessesing gateway 13

acessesing gateway 13

acessesing gateway 13

acessesing gateway 13

acessesing gateway 13

acessesing gateway 13

acessesing gateway 13

I like run the same function with different input

Expected output for every 30s

acessesing gateway 1

acessesing gateway 2

acessesing gateway 3

acessesing gateway 4

acessesing gateway 5

acessesing gateway 6

acessesing gateway 7

acessesing gateway 8

acessesing gateway 9

acessesing gateway 10

  • 写回答

1条回答 默认 最新

  • doudi1979 2019-07-18 13:32
    关注

    Problem in your code is equivalent to the one described here:

    https://github.com/golang/go/wiki/CommonMistakes#using-goroutines-on-loop-iterator-variables

    To fix it:

    for _, va := range devices {
        va := va // create a new "va" variable on each iteration
        c.AddFunc("@every 30s", func() { test(va) })
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀