doupao1978 2018-07-18 11:24
浏览 404
已采纳

如何有效停止Gocron工作?

I am doing something like this:

package main

import (
    "fmt"
    "time"

    "github.com/jasonlvhit/gocron"
)

func jobs(quit <-chan bool) {
    for {
        select {
        case <-quit:
            return
        default:
            //cron jobs
            g := gocron.NewScheduler()
            g.Every(1).Second().Do(stuff)
            <-g.Start()
        }
    }
}

func stuff() {
    fmt.Println("doing job")
}

func main() {
    q := make(chan bool)
    go jobs(q)
    time.Sleep(3 * time.Second)

 //to quit the goroutine
    q <- true    
    close(q)
    fmt.Println("main")
}

I'm trying to stop the gocrons by killing the goroutine by closing the channel but I'm not able to stop gocron jobs. I am getting output

            doing job
            doing job
            doing job
            doing job
            doing job
            doing job
            doing job
            .
            .

Instead of

            doing job
            doing job
            doing job
            main

What am I doing wrong? Is there any better solution to stop gocron jobs?

  • 写回答

1条回答 默认 最新

  • douxin1956 2018-07-18 13:14
    关注

    Your problem is in the select block here:

        select {
        case <-quit:
            return
        default:
            //cron jobs
            g := gocron.NewScheduler()
            g.Every(1).Second().Do(stuff)
            <-g.Start()
        }
    

    This code says: select the case we can read from quit and exit, or do the default case.

    Entering the default part of the case will block the goroutine on <-g.Start() until all the jobs are done. We have to wait here for the jobs to finish. While we are still waiting on <-g.Start() we do not consider the quit channel.

    Instead do:

    func jobs(quit <-chan bool) {
        for {
            //cron jobs
            g := gocron.NewScheduler()
            g.Every(1).Second().Do(stuff)
    
            select {
            case <-quit:
                // here we receive from quit and exit
                // if `g` has started, we may want to `g.Clear()`
                // or the scheduled jobs will continue, we will just not be waiting for them to finish.
                return
            case <-g.Start():
                // here we know all the jobs are done, and go round the loop again
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘