Introduction
In this blog, we are looking at what are tickers & epochs in Go and how we can use tickers & epochs effectively within your own Go applications.
Tickers
When we wish to do some work at regular intervals, we use Go Tickers. The Stop() method can be used to stop tickers in the same way as it can stop timers.
The NewTicker() method creates a new Ticker with a channel that delivers the time based on the duration input. The time limit must be greater than zero. The Ticker will panic if this does not happen.
Tick() is a wrapper for NewTicker, which allows you to access the ticking channel. Clients who do not want to turn off the Ticker can use the Tick() method.
Example
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("Go Tickers ")
// this creates a new ticker which will
// `tick` every 1 second.
ticker := time.NewTicker(1 * time.Second)
// for every `tick` that our `ticker`
// emits, we print `tock`
for _ = range ticker.C {
fmt.Println("tock")
}
}
Output
Go Tickers
Tock
Tock
^Csignal: interrupt
This example for showing how we can use tickers.