CRON job in GO not running as expected

时间:2017-04-10 02:18:47

标签: go

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.

2 个答案:

答案 0 :(得分:1)

Your code does this:

  1. Initiates a new cron instance:

    c := cron.New()
    
  2. Adds a cron job:

    c.AddFunc("@every 3m", func() { fmt.Println("Every 3 min") })
    
  3. Starts the cron instance in a new goroutine (in the background):

    c.Start()
    
  4. Prints "Done":

    fmt.Println("Done")
    
  5. 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 {}
}