frankegoesdown
frankegoesdown

Reputation: 1924

ticker still live in memory

Why when I initialize ticker and then update it, original ticker still live in memory and if I make for loop it will kill my RAM very soon

timeOut := 10
ticker := time.NewTicker(time.Duration(timeOut) * time.Second)
for {
    ticker = time.NewTicker(time.Duration(timeOut) * time.Second)
}

Upvotes: 0

Views: 438

Answers (2)

erik258
erik258

Reputation: 16275

for {
    ticker = time.NewTicker(time.Duration(timeOut) * time.Second)
}

That's going to create ticker instances as fast as possible, and because of the nature of ticker objects they won't be able to clean up ( they're referenced by the implementation of ticket which, due to its async nature, happens in a different goroutine). Go can do this very quickly, resulting in OOM ( out of memory) error very rapidly.

But this pattern doesn't make any sense. There's no good reason to create new tickers like this in a for loop. You can create multiple tickers, even very many of them, but you can't create infinite tickers, nor does it make much sense to do so.

Further, notice you're not actually using your tickers anywhere. Consider the example here: https://gobyexample.com/tickers . You'll see how they interact with the ticker to make code run with each tick. Note the ticker there is created once, not in a loop.

Upvotes: 2

peterSO
peterSO

Reputation: 166529

Package time

import "time"

func NewTicker

func NewTicker(d Duration) *Ticker

NewTicker returns a new Ticker containing a channel that will send the time with a period specified by the duration argument. It adjusts the intervals or drops ticks to make up for slow receivers. The duration d must be greater than zero; if not, NewTicker will panic. Stop the ticker to release associated resources.


Follow the instructions: Stop the ticker to release associated resources.

Upvotes: 3

Related Questions