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?
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
}
}
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加