0

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.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
pyprism
  • 2,928
  • 10
  • 46
  • 85

2 Answers2

3

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

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.

Community
  • 1
  • 1
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189