Q:

Golang program to print the received value from the ticker

belongs to collection: Golang Timers & Tickers Programs

0

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

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 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 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.

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

total answers (1)

Golang program to implement a global ticker... >>
<< Golang program to implement the multiple tickers...