Golang program to stop the timer explicitly

Here, we are going to learn how to stop the timer explicitly in Golang (Go Language)?
Submitted by Nidhi, on April 28, 2021

Problem Solution:

Here, we will implement a timer for 3 seconds using time.NewTimer() function and received notification in a go function. Here we stopped the timer using the Stop() function explicitly.

Program/Source Code:

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

//Golang program to stop timer explicitly.
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.

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

	log.Println("During timer time")

	time.Sleep(1 * time.Second)
	result := MyTimer.Stop()

	if result == true {
		log.Println("Stopped timer explicitly")
	time.Sleep(5 * time.Second)


2021/04/28 22:29:02 Timer Started
2021/04/28 22:29:02 During timer
2021/04/28 22:29:05 Timer finished


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 stopped the timer using the Stop() function explicitly.

Golang Timers & Tickers Programs »

Comments and Discussions

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.