英文:
CRON job in Go not running as expected
问题
这是我的代码:
package main
import (
"fmt"
"github.com/robfig/cron"
)
func main() {
c := cron.New()
c.AddFunc("@every 3m", func() { fmt.Println("每隔3分钟") })
c.Start()
fmt.Println("完成")
}
问题是,当我使用go run
运行代码时,它只打印出完成
然后退出。我只是想每隔3分钟打印一次函数。
英文:
Here is my code:
package main
import (
"fmt"
"github.com/robfig/cron"
)
func main() {
c := cron.New()
c.AddFunc("@every 3m", func() { fmt.Println("Every 3 min") })
c.Start()
fmt.Println("Done")
}
The problem is when I run the code using go run
it just prints Done
then exits. I am just trying to print the function every 3 minute.
答案1
得分: 3
扩展@Flimzy的答案,如果你希望你的程序保持空闲状态,只需添加select {}
即可。
你的代码应该像这样:
func main() {
c := cron.New()
c.AddFunc("@every 3m", func() { fmt.Println("Every 3 min") })
c.Start()
fmt.Println("Done")
select {}
}
英文:
Extending on @Flimzy answer, if you want your program to sit and do nothing, just add select {}
to it
Your code would be something like this:
func main() {
c := cron.New()
c.AddFunc("@every 3m", func() { fmt.Println("Every 3 min") })
c.Start()
fmt.Println("Done")
select {}
}
答案2
得分: 2
你的代码做了以下几件事情:
-
初始化了一个新的
cron
实例:c := cron.New()
-
添加了一个 cron 作业:
c.AddFunc("@every 3m", func() { fmt.Println("Every 3 min") })
-
在一个新的 goroutine(后台)中启动了 cron 实例:
c.Start()
-
打印了 "Done":
fmt.Println("Done")
-
然后退出。
如果你希望程序继续运行,你需要让它执行一些使其保持运行的操作。如果没有其他需要程序执行的任务,你可以让它等待一个永远不会结束的任务完成。可以参考这个答案中的一些建议。
英文:
Your code does this:
-
Initiates a new
cron
instance:c := cron.New()
-
Adds a cron job:
c.AddFunc("@every 3m", func() { fmt.Println("Every 3 min") })
-
Starts the cron instance in a new goroutine (in the background):
c.Start()
-
Prints "Done":
fmt.Println("Done")
-
Then exits.
If you want your program to keep running, you need to make it do something that keeps it running. If there is nothing else you need your program to do, just have it wait for something to finish that never finishes. See this answer for some suggestions along those lines.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论