Friday, March 3, 2017

golang run code at timed intervals

If you come from a Javascript background, you might be accustomed to setInterval.

In Golang if you want to run code a set interval you would do the following.

package main

import (
"fmt"
"time"
)

func main() {
ticker := time.NewTicker(time.Second)
for time := range ticker.C {

fmt.Printf("we run at %s\n", time.String())
}
}

The code inside will be called every second, as defined in time.NewTicker().

No comments:

Post a Comment