Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a Go method using cron

Tags:

go

cron

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("----")
}
like image 595
AFraser Avatar asked Mar 05 '15 05:03

AFraser


2 Answers

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())
}
like image 164
LenW Avatar answered Oct 02 '22 16:10

LenW


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)

like image 34
serejja Avatar answered Oct 02 '22 14:10

serejja