running a function periodically in go

I suggest to checkout this package. https://godoc.org/github.com/robfig/cron

You can even use seconds.

c := cron.New(cron.WithSeconds())
c.AddFunc("*/5 * * * * *", func() { fmt.Println("Testing every 5 seconds.") })
c.Start()

Use a time.Ticker. There's many ways to structure the program, but you can start with a simple for loop:

uptimeTicker := time.NewTicker(5 * time.Second)
dateTicker := time.NewTicker(10 * time.Second)

for {
    select {
    case <-uptimeTicker.C:
        run("uptime")
    case <-dateTicker.C:
        run("date")
    }
}

You may then want to run the commands in a goroutine if there's a chance they could take longer than your shortest interval to avoid a backlog in the for loop. Alternatively, each goroutine could have its own for loop with a single Ticker.


func main() {
    for range time.Tick(time.Second * 10) {
        function_name()
    }
}

Tags:

Concurrency

Go