Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to explicitly stop a ticker whose reference has been reassigned?

Tags:

go

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?

like image 726
theeddieh Avatar asked Oct 15 '25 15:10

theeddieh


2 Answers

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.

like image 179
John S Perayil Avatar answered Oct 18 '25 08:10

John S Perayil


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.

like image 43
Asteriskdev Avatar answered Oct 18 '25 07:10

Asteriskdev