Tickers
Use time.Ticker
to perform a task periodically. You will periodically receive a signal through a channel. Unlike time.Timer
, you have to be careful about how you dispose of tickers. If you forget to stop a ticker, it will not be garbage collected once it is out of scope, and it will leak.
How to do it...
- Use
time.Ticker
to create a new ticker. - Read from the ticker’s channel to receive the periodic ticks.
- When you are done with the ticker, stop it. You don’t have to drain the ticker’s channel.
How it works...
Use a ticker for periodic events. A common pattern is the following:
func poorMansClock(done chan struct{}) { // Create a new ticker with a 1 second period ticker:=time.NewTicker(time.Second) // Stop the ticker once we're done defer ticker.Stop() for { select { case <-done: ...