Timers

Often, we want to run Go code at some point in the future or repeatedly at some interval. Go's built-in timers and tickers features make these two tasks easy.

We will look at the timers first and then the tickers.

Timers represent a single event in the future. You tell the timer how long you want to wait and it gives you a channel that will be notified at that time.


time.NewTimer(time.Duration)
                        

<-timer1.C blocks on the timer's C channel until it sends a value indicating that the timer has fired.

If you just wanted to wait, you could have used the time.Sleep function. One reason why a timer can be useful is that you can cancel it before it fires.

timers.go