Golang program to perform some other activities with the ticker

Here, we are going to learn how to perform some other activities with the ticker in Golang (Go Language)?
Submitted by Nidhi, on April 28, 2021 [Last updated : March 04, 2023]

How to perform some other activities with the ticker in Golang?

Problem Solution:

Here, we will implement a global ticker using time.NewTicker() function and get a tick in every second as well as perform some other activities.

Program/Source Code:

The source code to perform some other activities with ticker is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

Golang code to perform some other activities with the ticker

// Golang program to perform some other
// activities with the ticker

package main

import "log"
import "fmt"
import "time"

func main() {
	MyTicker := time.NewTicker(1 * time.Second)

	log.Println("Ticker started")

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

	for i := 0; i < 5; i++ {
		fmt.Println("Other activities")
		time.Sleep(1 * time.Second)
	}
	log.Println("Ticker finished")
}

Output:

2021/04/28 04:14:15 Ticker started
Other activities
2021/04/28 04:14:16 Tick Received
Other activities
2021/04/28 04:14:17 Tick Received
Other activities
2021/04/28 04:14:18 Tick Received
Other activities
2021/04/28 04:14:19 Tick Received
Other activities
2021/04/28 04:14:20 Tick Received
2021/04/28 04:14:20 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 a ticker MyTicker using time.NewTicker() function and receive notification in every 1 second. Here we also printed the "Other activities" message simultaneously on the console screen.

Golang Timers & Tickers Programs »





Comments and Discussions!

Load comments ↻





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