×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang program to implement a global ticker

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

Implementing a global ticker in Golang

Problem Solution:

Here, we will implement a global ticker using time.NewTicker() function and get a tick in every second for infinite time.

Program/Source Code:

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

Golang code to implement a global ticker

// Golang program to implement a global ticker

package main

import "log"
import "time"

var MyTicker *time.Ticker

func initTicker() {
	MyTicker = time.NewTicker(1 * time.Second)
}

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

func main() {
	log.Println("Ticker started")
	initTicker()

	recvTick()

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

Output:

2021/04/28 04:07:21 Ticker started
2021/04/28 04:07:22 Tick Received
2021/04/28 04:07:23 Tick Received
2021/04/28 04:07:24 Tick Received
2021/04/28 04:07:25 Tick Received
2021/04/28 04:07:26 Tick Received
2021/04/28 04:07:27 Tick Received
2021/04/28 04:07:28 Tick Received
2021/04/28 04:07:29 Tick Received
2021/04/28 04:07:30 Tick Received
...
...

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 functions initTicker() and recvTick() to implement global ticker and got tick in every 1 second for infinite time.

Golang Timers & Tickers Programs »





Comments and Discussions!

Load comments ↻





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