我正在做这样的事情:
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")
}
我正在尝试通过关闭渠道杀死goroutine来停止gocrons,但我无法停止gocron作业。我正在输出
doing job
doing job
doing job
doing job
doing job
doing job
doing job
.
.
代替
doing job
doing job
doing job
main
我究竟做错了什么?有没有更好的解决方案来停止Gocron工作?
最佳答案
您的问题在此处的选择块中:
select {
case <-quit:
return
default:
//cron jobs
g := gocron.NewScheduler()
g.Every(1).Second().Do(stuff)
<-g.Start()
}
这段代码说:选择我们可以从
quit
中读取的大小写并退出,或者执行默认大小写。输入案例的
default
部分将阻止<-g.Start()
上的goroutine,直到完成所有作业。我们必须在这里等待工作完成。当我们仍在等待<-g.Start()
时,我们不考虑quit
频道。而是:
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
}
}
}
关于go - 如何有效停止Gocron工作?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51400831/