time.NewTimer() Function in Golang With Examples

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:



filter_none

edit
close

play_arrow

link
brightness_4
code

// 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")
}

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
}

chevron_right


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.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.