In Go language, time packages supplies functionality for determining as well as viewing time. The NewTicker() function in Go language is used to output a new Ticker that contains a channel in order to transmit the time with a period as stated by the duration parameter. It is helpful in setting the intervals or dropping the ticks of the ticker in order to make up for the slow recipients. Here, the duration ‘d’ must be greater than zero else a panic error will occur. And you can terminate the ticker by using the Stop() method in order to liberate the related resources. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func NewTicker(d Duration) *Ticker
Here, “d” is the duration and *Ticker is a pointer to the Ticker. Where, the Ticker is used to hold a channel that supplies `ticks’ of a clock at intervals.
Return value: It returns a new Ticker that includes a channel.
Example 1:
// Golang program to illustrate the usage of // time.NewTicker() function // Including main package package main // Importing fmt and time import "fmt"
import "time"
// Calling main func main() { // Calling NewTicker method
d := time .NewTicker(2 * time .Second)
// Creating channel using make
// keyword
mychannel := make(chan bool )
// Calling Sleep() methpod in go
// function
go func() {
time .Sleep(7 * time .Second)
// Setting the value of channel
mychannel <- true
}()
// Using for loop
for {
// Select statement
select {
// Case statement
case <-mychannel:
fmt.Println( "Completed!" )
return
// Case to print current time
case tm := <-d.C:
fmt.Println( "The Current time is: " , tm )
}
}
} |
Output:
The Current time is: 2020-04-08 14:54:20.143952489 +0000 UTC m=+2.000223531 The Current time is: 2020-04-08 14:54:22.143940032 +0000 UTC m=+4.000211079 The Current time is: 2020-04-08 14:54:24.143938623 +0000 UTC m=+6.000209686 Completed!
Here, for loop is used in order to print the current time until loop stops and this time is printed after a regular interval that is after a “tick” as specified in the code. And here it is 2 seconds. So, the current time is printed above after a regular interval of 2 seconds. Here, the ticker must stop after three times as the limit is 7 seconds and only 1 second is left after the third tick.