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 :)
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!