In this tutorial, we’ll demonstrate a simple Golang ticker example utilizing the time package and Goroutines. Tickers are handy for executing tasks at regular intervals, and Goroutines provide a lightweight way to manage concurrent operations.
What’s Inside
Introduction to Tickers in Go
Golang provides built-in timers and tickers through the time package. Timers execute tasks once in the future, while tickers repeatedly run tasks at defined intervals. Both timers and tickers can be stopped using the Stop()
method.
Implementing a Ticker with Goroutines
Let’s create a Golang program that showcases the use of tickers in conjunction with Goroutines. The example involves creating a ticker that counts down for 4 seconds.
Step 1: Import Required Packages
package main import ( "fmt" "time" )
We import the necessary packages – fmt
for printing data and time
for working with tickers.
Step 2: Define the Main Function
func main() { fmt.Println("Hey! Wait for 4 seconds...") ticker := time.NewTicker(time.Second * 1) go tickerClock(ticker) time.Sleep(4 * time.Second) ticker.Stop() }
In the main()
function, we create a new ticker using NewTicker()
and initiate a Goroutine to execute the tickerClock
function. We then pause the main Goroutine for 4 seconds using time.Sleep()
and stop the ticker afterward.
Step 3: Implement the tickerClock Function
func tickerClock(ticker *time.Ticker) { i := 1 for t := range ticker.C { fmt.Println("Tick", i, "at", t) i++ } }
The tickerClock
function takes a Ticker
type variable and runs a loop, printing the tick count and timestamp for each tick.
Conclusion
This Golang example illustrates the simplicity of using tickers and Goroutines to achieve concurrent tasks with scheduled intervals. Feel free to explore more about Goroutines and time-related functionalities in Go for your projects.
Check Also: