Timers
Use time.Timer to schedule some work to be done in the future. When the timer expires, you will receive a signal from a channel. You can use a timer to run a function later or to cancel a process that ran too long.
How to do it...
You can create a timer in one of two ways:
- Use
time.NewTimerortime.After. The timer will send a signal through a channel when it expires. Use aselectstatement, or read from the channel to receive the timer expiration signal. - Use
time.AfterFuncto call a function when the timer expires.
How it works...
A time.Timer timer is created with time.Duration:
// Create a 10-second timer timer := time.NewTimer(time.Second*10)
The timer contains a channel that will receive the current timestamp after 10 seconds pass. A timer is created with a channel capacity of 1, so the timer runtime will always be able to write to that channel and stop the timer. In other words, if you fail to read from a timer, it will not leak; it will...