Golang program to stop a ticker explicitly

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

Problem Solution:

Here, we will implement a global ticker using time.NewTicker() function and get a tick every second. Here, we stopped the created ticker explicitly using the Stop() function.

Program/Source Code:

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

// Golang program to stop a ticker explicitly

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")

		if i == 2 {
			MyTicker.Stop()
			log.Println("Ticker Stopped")
		}
		time.Sleep(1 * time.Second)
	}

	log.Println("Program finished")
}

Output:

2021/04/28 05:48:05 Ticker started
Other activities
2021/04/28 05:48:06 Tick Received
Other activities
2021/04/28 05:48:07 Tick Received
Other activities
2021/04/28 05:48:07 Ticker Stopped
Other activities
Other activities
2021/04/28 05:48:10 Program 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 stopped the specified ticker 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.