本文介绍了gocron创建多个任务实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在使用这个包的脚本中遇到问题:
github.com/jasonlvhit/gocron
在我找不到错误之后,我写了这个小小的测试脚本,导致执行了两倍的cronjobs按照预期:
func main(){
for i:= 0;我< 3; i ++ {
channel:= make(chan string)
go taskCron(channel,i)
}
time.Sleep(time.Second * 5)
gocron.Clear()
fmt.Println(stop this shit)
}
func任务(i int){
fmt.Println(仍然在运行......,i)
}
func taskCron(channel chan string,i int){
gocron.Every(4).Seconds().Do任务,i)
}
运行它给了我这个输出:
- ▶运行* .go
仍在运行... 0
仍在运行... 0
仍在运行中... 1
仍在运行中... 1
仍在运行中... 2
仍在运行... 2
仍在运行... 0
仍在运行... 1
仍在运行... 2
停止此
有谁知道如何创建动态数量的gocron作业而不复制它们?
感谢:)
解决方案
确定显然
< -gocron.Start()
将启动已经启动的作业,以便解决我的问题,我必须将脚本更改为:
func main(){
for i:= 0;我< 3; i ++ {
taskCron(i)
}
channel2:= make(chan int)
go startCron(channel2)
time.Sleep(time。秒* 5)
gocron.Clear()
fmt.Println(stop this)
}
func任务(i int){
fmt.Println(仍在运行...,i)
}
func taskCron(i int){
gocron.Every(4).Seconds()。 (任务,i)
}
func startCron(channel chan int){
}
我希望这可以帮助任何有同样问题的人!
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!
这篇关于gocron创建多个任务实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!