Open In App

time.NewTimer() Function in Golang With Examples

Improve
Improve
Like Article
Like
Save
Share
Report

In Go language, time packages supplies functionality for determining as well as viewing time. The NewTimer() function in Go language is used to create a new Timer that will transmit the actual time on its channel at least after duration “d”. 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 NewTimer(d Duration) *Timer

Here, *Timer is a pointer to the Timer.

Return Value: It returns a channel that notifies how long a timer will have to wait.

Example 1:




// Golang program to illustrate the usage of
// NewTimer() function
  
// Including main package
package main
  
// Importing fmt and time
import (
    "fmt"
    "time"
)
  
// Main function
func main() {
  
    // Calling NewTimer method
    newtimer := time.NewTimer(5 * time.Second)
  
    // Notifying the channel
    <-newtimer.C
  
    // Printed after 5 seconds
    fmt.Println("Timer is inactivated")
}


Output:

Timer is inactivated

Here, the above output is printed after 5 seconds of running the code, as after that stated time the channel is being notified that the timer is inactivated.

Example 2:




// Golang program to illustrate the usage of
// NewTimer() function
  
// Including main package
package main
  
// Importing fmt and time
import (
    "fmt"
    "time"
)
  
// Main function
func main() {
  
    // Calling NewTimer method
    newtimer := time.NewTimer(time.Second)
  
    // Notifying channel under go function
    go func() {
        <-newtimer.C
  
        // Printed when timer is fired
        fmt.Println("timer inactivated")
    }()
  
    // Calling stop method to stop the
    // timer before inactivation
    stoptimer := newtimer.Stop()
  
    // If the timer is stopped then the
    // below string is printed
    if stoptimer {
        fmt.Println("The timer is stopped!")
    }
  
    // Calling sleep method to stop the
    // execution at last
    time.Sleep(4 * time.Second)
}


Output:

The timer is stopped!

In the above method, the timer is being stopped before inactivating as here the stop method is being called to stop the timer. And at last, the program is exited using sleep method.



Last Updated : 21 Apr, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads