英文:
gocron creates multiple instances of task
问题
我在使用这个包时遇到了一个问题:
"github.com/jasonlvhit/gocron"
在我找不到错误的情况下,我编写了这个小测试脚本,结果发现执行的cron作业是预期的两倍:
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()
}
运行它给了我这个输出:
——▶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
有人知道如何创建动态数量的gocron作业而不重复它们吗?
谢谢
英文:
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
答案1
得分: 3
好的,以下是翻译好的内容:
好像是这样的
<-gocron.Start()
会重新启动已经启动的作业,所以为了解决我的问题,我必须将脚本更改为以下内容:
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("停止")
}
func task(i int) {
fmt.Println("仍在运行...", i)
}
func taskCron(i int) {
gocron.Every(4).Seconds().Do(task, i)
}
func startCron(channel chan int) {
<-gocron.Start()
}
希望这对于遇到相同问题的人有所帮助!
英文:
Ok apparently
<-gocron.Start()
will start jobs that were already started 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!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论