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.
答案 0 :(得分:1)
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.
答案 1 :(得分:0)
扩展@Flimzy答案,如果您想让程序坐着不做任何事情,只需在其中添加select {}
您的代码将如下所示:
func main() {
c := cron.New()
c.AddFunc("@every 3m", func() { fmt.Println("Every 3 min") })
c.Start()
fmt.Println("Done")
select {}
}