golang tutorial - Timer In Golang | Golang timer example - golang - go programming language - google go - go language - go program - google language



Timer In Golang

  • The Timer allows you to set a time interval to periodically execute an event at a specified interval.
  • It is useful when you want to execute certain applications after a certain interval.
  • Say you want to create a hourly backup of your data.
  • You can make a routine that will take the backup and call that routine in the Timer's event and set the timer interval for an hour.
  • Generates an event after a set interval, with an option to generate recurring events.
  • Go’s built-in timer and ticker features make both of these tasks easy.
 if statement
package main

	import "time"
import "fmt"

	func main() {
// Timers represent a single event in the future. You tell the timer how long you want to wait, and it provides a channel that will be notified at that time. This timer will wait 2 seconds.

//The <-timer1.C blocks on the timer’s channel C until it sends a value indicating that the timer expired.
	    timer1 := time.NewTimer(time.Second * 2)

	    <-timer1.C
    fmt.Println("Timer 1 expired")
// If you just wanted to wait, you could have used time.Sleep. One reason a timer may be useful is that you can cancel the timer before it expires. Here’s an example of that.
	    timer2 := time.NewTimer(time.Second)
    go func() {
        <-timer2.C
        fmt.Println("Timer 2 expired")
    }()
    stop2 := timer2.Stop()
    if stop2 {
        fmt.Println("Timer 2 stopped")
    }
}
click below button to copy the code. By - golang tutorial - team
 if statement
golang , gopro , google go , golang tutorial , google language , go language , go programming language

Output for the above go language program

 // The first timer will expire ~2s after we start the program, but the second should be stopped before it has a chance to expire.
	$ go run timers.go
Timer 1 expired
Timer 2 stopped

Related Searches to Timer In Golang | Golang timer example