I'm using time.Ticker to do some stuff at a regular interval. I want to be able to change the frequency that stuff happens at:
for {
select {
case <-ticker.C:
//do stuff
case t := <-newTicker:
oldTicker := ticker
ticker = t
oldTicker.Stop()
}
}
Do I need that ticker cleanup to avoid a memory leak, or will reassigning ticker like
case ticker := <-newTicker:
be enough?
As JimB mentioned as per time package GoDoc.
Under time.NewTicker, the following is mentioned.
Stop the ticker to release associated resources.
Provided you run oldTimer.Stop(), oldTicker will get garbage collected after exiting the case statement as it's out of scope.
Instead of using a chan time.Ticker use a chan time.Duration and send a time.Duration to be used by the ticker's Reset() method.
for {
select {
case <-ticker.C:
//do stuff
case t := <-newTickerDuration: // (chan time.Duration)
ticker.Reset(t)
}
}
Send the new duration instead of a new ticker and call the ticker's Reset() method passing in the time.Duration that was received on the channel.
This will stop and reset the ticker with the new duration without the need to create a new ticker each time. The accepted answer does answer the question, but it would result in increased garbage collection and waste resources.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With