Golang Ticker loop to iterate over time.Tick channel


Tuan Nguyen

GO

I. Introduction to time.Tick channel

In this article, we are going through tickers in Go and the way to iterate a Go time.Tick channel.

There are often cases where we would want to perform a particular task after a specific interval of time repeatedly. In Golang, we achieve this with the help of tickers. We can create a ticker by NewTicker() function and stop it by Stop() function. These two functions are described in the below table:

Name Description
func NewTicker(d Duration) *Ticker NewTicker returns a new Ticker containing a channel that will send the current time on the channel after each tick. The period of the ticks is specified by the duration argument.
func (t *Ticker) Stop() Stop turns off a ticker. After Stop, no more ticks will be sent. Stop does not close the channel, to prevent a concurrent goroutine reading from the channel from seeing an erroneous "tick".

 

II. Example 1: Using Golang ticker loop with Stop() function

In this example, we will create a ticker with a for loop and iterate it in another goroutine. After 7s, we call Stop() function to turn off the ticker.

package main

import (
	"fmt"
	"time"
)

func main() {
	ticker := time.NewTicker(2 * time.Second)

	// Creating channel using make
	tickerChan := make(chan bool)

	go func() {
		// Using for loop
		for {
			// Select statement
			select {
			// Case statement
			case <-tickerChan:
				return

			// Case to print current time
			case tm := <-ticker.C:
				fmt.Println("The Current time is: ", tm)
			}
		}
	}()

	// Calling Sleep() method
	time.Sleep(7 * time.Second)

	// Calling Stop() method
	ticker.Stop()

	// Setting the value of channel
	tickerChan <- true

	// Printed when the ticker is turned off
	fmt.Println("Ticker is turned off!")
}

Output:

The Current time is:  2022-09-11 21:42:57.3287283 +0700 +07 m=+2.011840401
The Current time is:  2022-09-11 21:42:59.3279005 +0700 +07 m=+4.011012601
The Current time is:  2022-09-11 21:43:01.3249886 +0700 +07 m=+6.008100701
Ticker is turned off!

Explanation: Firstly, a Ticker is created, then a channel is created that transmits time. After that, a loop is used in order to print the current time, then the Ticker.Stop() method is called and the ticker is turned off. Once a ticker is stopped it won’t receive any more values on its channel.

 

II. Example 2: Using condition to break the Ticker loop

Here's an example of using a ticker to call a function every 3 seconds until it is called 5 times. After the function is call 5 times, we will break the loop.

package main

import (
	"fmt"
	"time"
)

func main() {
	fmt.Println("Start Ticker Example 1")

	// define an interval and the ticker for this interval
	interval := time.Duration(2) * time.Second
	// create a new Ticker
	tk := time.NewTicker(interval)
	// start the ticker by constructing a loop
	i := 0
	for range tk.C {
		i++
		countFuncCall(i)
		if i > 4 {
			break
		}
	}
}

// define the function
func countFuncCall(i int) {
	fmt.Println("Function is called: ", i, "times")
}

Output:

Start Ticker Example 1
Function is called:  1 times
Function is called:  2 times
Function is called:  3 times
Function is called:  4 times
Function is called:  5 times

Explanation: We create a variable 'i' to count the number of times the function is executed. For example, we want to execute the function 5 times so when the counter is greater than 4, we exit from the golang ticker loop.

 

IV. Summary

In this article, I demonstrated two methods for using Tickers. We can use Stop() function or initialize condition to break the loop.  Tickers and goroutines can be combined in a variety of ways to create background tasks. You can learn more about tickers by reading Golang Ticker Explained in Detail [With Examples].

 

V. References

https://pkg.go.dev/time#Tick
How do I iterate over a go time.Tick channel?

 

Views: 13

Tuan Nguyen

He is proficient in Golang, Python, Java, MongoDB, Selenium, Spring Boot, Kubernetes, Scrapy, API development, Docker, Data Scraping, PrimeFaces, Linux, Data Structures, and Data Mining. With expertise spanning these technologies, he develops robust solutions and implements efficient data processing and management strategies across various projects and platforms. You can connect with him on LinkedIn.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment

GoLinuxCloud Logo


We try to offer easy-to-follow guides and tips on various topics such as Linux, Cloud Computing, Programming Languages, Ethical Hacking and much more.

Programming Languages

JavaScript

Python

Golang

Node.js

Java

Laravel