×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang program to implement the ticker for every second

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

Implementing the ticker for every second in Golang

Problem Solution:

Here, we will implement a ticker for 1 second using time.NewTicker() function. Here, we will get a notification at every second.

Program/Source Code:

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

Golang code to implement the ticker for every second

// Golang program to implement ticker
// for every second

package main

import "log"
import "time"

func main() {
	MyTicker := time.NewTicker(1 * time.Second)

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

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

Output:

2021/04/28 03:41:44 Tick Received
2021/04/28 03:41:45 Tick Received
2021/04/28 03:41:46 Tick Received
2021/04/28 03:41:47 Tick Received
2021/04/28 03:41:48 Tick Received
2021/04/28 03:41:49 Tick Received
2021/04/28 03:41:49 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 using time.NewTicker() function for 1 second and get the notification in every second and then printed the "Tick Received" message with timestamp on the console screen.

Golang Timers & Tickers Programs »





Comments and Discussions!

Load comments ↻





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