Golang program to implement the timer

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

Implementing the timer in Golang

Problem Solution:

Here, we will implement a timer for 3 seconds using time.NewTimer() function.

Program/Source Code:

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

Golang code to implement the timer

// Golang program to implement the timer
// using time.NewTimer() function

package main

import "log"
import "time"

func main() {
	//Start timer for 3 seconds
	MyTimer := time.NewTimer(3 * time.Second)

	log.Println("Timer Started")
	// Notification received when timer gets in-activated.
	<-MyTimer.C

	log.Println("Timer finished")
}

Output:

2021/04/28 05:57:18 Timer Started
2021/04/28 05:57:21 Timer 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 timer using time.NewTimer() function and wait for the notification of timer using the created channel. Here, we printed messages before and after the timer with timestamp on the console screen.

Golang Timers & Tickers Programs »






Comments and Discussions!

Load comments ↻






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