duanju8431 2017-06-25 11:52
浏览 124
已采纳

gocron创建任务的多个实例

I had a problem in a script using this package:

    "github.com/jasonlvhit/gocron"

I wrote this little testscript after I couldn't find a mistake and it resulted that there were twice as many cronjobs executed as intended:

func main() {
    for i := 0; i < 3; i++ {
        channel := make(chan string)
        go taskCron(channel, i)
    }

    time.Sleep(time.Second * 5)
    gocron.Clear()
    fmt.Println("stop this shit")
}

func task(i int) {
    fmt.Println("still running...", i)
}

func taskCron(channel chan string, i int) {
    gocron.Every(4).Seconds().Do(task, i)
    <-gocron.Start()
}

running it gave me this output:

——▶go run *.go
still running... 0
still running... 0
still running... 1
still running... 1
still running... 2
still running... 2
still running... 0
still running... 1
still running... 2
stop this

Does anyone know how I can create a dynamic amount of gocron jobs without duplicating them?

Thanks :)

  • 写回答

1条回答 默认 最新

  • dongxiong1941 2017-06-25 12:06
    关注

    Ok apparently

    <-gocron.Start()
    

    will start jobs that were already startet again so to fix my issue, I had to change the script to this:

    func main() {
        for i := 0; i < 3; i++ {
            taskCron(i)
        }
        channel2 := make(chan int)
        go startCron(channel2)
    
        time.Sleep(time.Second * 5)
        gocron.Clear()
        fmt.Println("stop this")
    }
    
    func task(i int) {
        fmt.Println("still running...", i)
    }
    
    func taskCron(i int) {
        gocron.Every(4).Seconds().Do(task, i)
    }
    
    func startCron(channel chan int) {
        <-gocron.Start()
    }
    

    I hope this helps anybody who had the same Problem!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站