Q:

Golang program to implement the multiple tickers

belongs to collection: Golang Timers & Tickers Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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 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 MyTicker1MyTicker2 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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Golang program to print the received value from th... >>
<< Golang program to implement the ticker for every s...