Open In App

time.Ticker.Stop() Function in Golang With Examples

Improve
Improve
Like Article
Like
Save
Share
Report

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




// Golang program to illustrate the usage of
// time.Ticker.Stop() function
 
// Including main package
package main
 
// Importing fmt and time
import "fmt"
import "time"
 
// Calling main
func main() {
 
    // Calling NewTicker method
    Ticker := time.NewTicker(2 * time.Second)
 
    // Creating channel using make
    // keyword
    mychannel := make(chan bool)
 
    // Go function
    go func() {
 
        // Using for loop
        for {
 
            // Select statement
            select {
 
            // Case statement
            case <-mychannel:
                return
 
            // Case to print current time
            case tm := <-Ticker.C:
                fmt.Println("The Current time is: ", tm)
            }
        }
    }()
 
    // Calling Sleep() method
    time.Sleep(7 * time.Second)
 
    // Calling Stop() method
    Ticker.Stop()
 
    // Setting the value of channel
    mychannel <- true
 
    // Printed when the ticker is turned off
    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.



Last Updated : 13 May, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads