Running the Go method using cron

I am trying to write a program that will continuously call a method at a specific time interval. I use the cron library to try to achieve this, but when I run the program, it simply executes and finishes with any output.

Below is a basic example of what I'm trying to do.

Help was 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("----")
}
+4
source share
3 answers

You can wait for the OS to inform you, for example. CTRL-C from the user. Also your cron expression was for every minute, that is, only where the 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())
}
+7
source

, c.Start() goroutine, c.Start . https://github.com/robfig/cron/blob/master/cron.go#L125

, , - . - time.Sleep(1 * minute) ( <-make(chan struct{}), )

+4

Using an external package for this is redundant, timehas everything you need:

package main

import (
    "fmt"
    "time"
)

func main() {
    go func() {
        c := time.Tick(1 * time.Second)
        for range c {
            // Note this purposfully runs the function
            // in the same goroutine so we make sure there is
            // only ever one. If it might take a long time and
            // it safe to have several running just add "go" here.
            RunEverySecond()
        }
    }()

    // Other processing or the rest of your program here.
    time.Sleep(5 * time.Second)

    // Or to block forever:
    //select {}
    // However, if doing that you could just stick the above for loop
    // right here without dropping it into a goroutine.
}

func RunEverySecond() {
    fmt.Println("----")
}

playground

+2
source

All Articles