Golang program to print the received value from the ticker

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

Printing the received value from the ticker in Golang

Problem Solution:

Here, we will implement a ticker using time.NewTicker() function and print notified value on the console screen.

Program/Source Code:

The source code to print the received value from the ticker is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

Golang code to print the received value from the ticker

// Golang program to print the received
// value from the ticker

package main

import "fmt"
import "time"

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

	go func() {
		for {
			val := <-MyTicker.C
			fmt.Println(val)
		}
	}()

	time.Sleep(6 * time.Second)
	fmt.Println("Ticker finished")
}

Output:

2021-04-28 03:59:58.608391459 +0000 UTC m=+1.048522317
2021-04-28 03:59:59.608418517 +0000 UTC m=+2.048549380
2021-04-28 04:00:00.60841732 +0000 UTC m=+3.048548182
2021-04-28 04:00:01.608429595 +0000 UTC m=+4.048560451
2021-04-28 04:00:02.60843223 +0000 UTC m=+5.048563089
2021-04-28 04:00:03.608450903 +0000 UTC m=+6.048581811
Ticker 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 for 1 second, and printed the notified value on the console screen.

Golang Timers & Tickers Programs »






Comments and Discussions!

Load comments ↻






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