I'm trying to write a program that will continuously call a method at a certain time interval. I'm using a cron library to try and achieve this but when I run the program it just executes and finishes with out any output.
Below is a basic example of what I'm trying to do.
Assistance greatly appreciated!
package main
import (
"fmt"
"github.com/robfig/cron"
)
func main() {
c := cron.New()
c.AddFunc("1 * * * * *", RunEverySecond)
c.Start()
}
func RunEverySecond() {
fmt.Println("----")
}
You can wait for the OS to signal you, e.g. CTRL-C from the user. Also your cron expression was for every minute, i.e. only where seconds == 1.
package main
import (
"fmt"
"os"
"os/signal"
"time"
"github.com/robfig/cron"
)
func main() {
c := cron.New()
c.AddFunc("* * * * * *", RunEverySecond)
go c.Start()
sig := make(chan os.Signal)
signal.Notify(sig, os.Interrupt, os.Kill)
<-sig
}
func RunEverySecond() {
fmt.Printf("%v\n", time.Now())
}
As you can see c.Start()
runs in another goroutine, so the call to c.Start
returns immediately. https://github.com/robfig/cron/blob/master/cron.go#L125
So your program finishes earlier than you see any output. You may add something like time.Sleep(1 * minute)
or have a close channel for this (or just <-make(chan struct{})
to wait eternally)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With