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!

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

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示