Q:

Golang program to implement the timer with go function

belongs to collection: Golang Timers & Tickers Programs

0

Here, we will implement a timer for 3 seconds using time.NewTimer() function and received notification in a go function then we can some other activities before finishing timer.

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 timer with the go function is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Golang program to implement timer
// with go function

package main

import "log"
import "time"

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

	log.Println("Timer Started")

	go func() {
		// Notification recived when timer gets in-activated.
		<-MyTimer.C

		// Printed when timer is fired
		log.Println("Timer finished")
	}()

	log.Println("During timer")

	time.Sleep(5 * time.Second)
}

Output:

2021/04/28 22:29:02 Timer Started
2021/04/28 22:29:02 During timer
2021/04/28 22:29:05 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 for 3 seconds and created a go function to wait for the notification of timer using the created channel. After that, we printed the message before finishing the timer. Here, we user timer.Sleep() function to hold the execution of the program to finish the timer.

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

total answers (1)

Golang program to stop the timer explicitly... >>
<< Golang program to implement the timer...