Golang program to implement the multiple tickers

Here, we are going to learn how to implement the multiple tickers in Golang (Go Language)?
Submitted by Nidhi, on April 28, 2021 [Last updated : March 04, 2023]

Implementing the multiple tickers in Golang

Problem Solution:

Here, we will implement two tickers using time.NewTicker() function. Here we will get the notification every second and 500 milliseconds.

Program/Source Code:

The source code to implement the multiple tickers is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

Golang code to implement the multiple tickers

// Golang program to implement the multiple tickers

package main

import "log"
import "time"

func main() {
	MyTicker1 := time.NewTicker(500 * time.Millisecond)
	MyTicker2 := time.NewTicker(1 * time.Second)

	go func() {
		for {
			<-MyTicker1.C
			log.Println("Tick Received for 500 millisecond")
		}
	}()

	go func() {
		for {
			<-MyTicker2.C
			log.Println("Tick Received 1 second")
		}
	}()

	time.Sleep(6 * time.Second)
	log.Println("Ticker finished")
}

Output:

2021/04/28 03:51:59 Tick Received for 500 millisecond
2021/04/28 03:52:00 Tick Received 1 second
2021/04/28 03:52:00 Tick Received for 500 millisecond
2021/04/28 03:52:00 Tick Received for 500 millisecond
2021/04/28 03:52:01 Tick Received 1 second
2021/04/28 03:52:01 Tick Received for 500 millisecond
2021/04/28 03:52:01 Tick Received for 500 millisecond
2021/04/28 03:52:02 Tick Received 1 second
2021/04/28 03:52:02 Tick Received for 500 millisecond
2021/04/28 03:52:02 Tick Received for 500 millisecond
2021/04/28 03:52:03 Tick Received for 500 millisecond
2021/04/28 03:52:03 Tick Received 1 second
2021/04/28 03:52:03 Tick Received for 500 millisecond
2021/04/28 03:52:04 Tick Received 1 second
2021/04/28 03:52:04 Tick Received for 500 millisecond
2021/04/28 03:52:04 Tick Received for 500 millisecond
2021/04/28 03:52:05 Ticker finished

Explanation:

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the required packages to predefined functions.

In the main() function, we created two ticker MyTicker1, MyTicker2 using time.NewTicker() function for 500ms and 1 second. Then we got the notification every 500ms and 1 second and then printed the "Tick Received" message with a timestamp on the console screen.

Golang Timers & Tickers Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.