time.Ticker.Stop() Function in Golang With Examples
Last Updated :
13 May, 2022
In Go language, time packages supply functionality for determining as well as viewing time. The Stop() function in Go language is used to disable a ticker. So, after calling Stop() method no further ticks will be transmitted. And it doesn’t close the channel, in order to avoid a concurrent go-routine reading from the channel from viewing an inaccurate “tick”. 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 (t *Ticker) Stop()
Here, “t” is a pointer to the Ticker. The Ticker is used to hold a channel that supplies `ticks’ of a clock at intervals.
Return Value: It returns the output of the stated operation before calling the stop() method because after calling it ticker is turned off.
Example:
C
package main
import "fmt"
import " time "
func main() {
Ticker := time .NewTicker(2 * time .Second)
mychannel := make(chan bool )
go func() {
for {
select {
case <-mychannel:
return
case tm := <-Ticker.C:
fmt.Println("The Current time is: ", tm )
}
}
}()
time .Sleep(7 * time .Second)
Ticker.Stop()
mychannel <- true
fmt.Println("Ticker is turned off!")
}
|
Output:
The Current time is: 2020-04-09 07:26:05.374436607 +0000 UTC m=+2.000213251
The Current time is: 2020-04-09 07:26:07.374442201 +0000 UTC m=+4.000218858
The Current time is: 2020-04-09 07:26:09.374511648 +0000 UTC m=+6.000288424
Ticker is turned off!
Here, at first a Ticker is created, then a channel is created that transmits time. After that, a loop is used in order to print the current time, then the Ticker.Stop() method is called and the ticker is turned off.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...