blue panther
blue panther

Reputation: 253

Should we stop this kind of Ticker?

I have a time ticker that will execute a function within time interval(eg every 5 minutes, 10 minutes). I create this time ticker within a goroutine. I heard that this kind of ticker could leak the memory even if the app stopped. This ticker will keep running as long as the app running. Should it stop? how to stop it properly? Here is my implementation:

go func() {
    for range time.Tick(5 * time.Minute) {
        ExecuteFunctionA()
    }
}()

What is the proper implementation for time ticker like this?

Upvotes: 2

Views: 1783

Answers (2)

canerbalci
canerbalci

Reputation: 1297

Nothing will leak if the 'app stopped'. The warning in the documentation refers to the fact that the garbage collector will not be able to reclaim the channel once it is created (time.Tick() initializes and returns a chan) and it will sit in memory even if you decide to break out of your for loop. Based on your description in the question, this shouldn't be an issue for you since you want the ticker running as long as the app is running. But if you decide otherwise, you can use an alternative way like:

go func() {
  for {
    time.Sleep(time.Duration(5) * time.Minute)
    go ExecuteFunctionA()
    if someConditionIsMet {
      break // nothing leaks in this case
    }
  }
}()

Upvotes: 2

pfctgeorge
pfctgeorge

Reputation: 718

You can use a channel as a intermediary to stop the ticker properly.

Usually, I did it as the following:

var stopChan chan bool = make(chan bool)

func Stop() {
    stopChan <- true
}

func Run() {
    go func() {
       ticker := time.NewTicker(5 * time.Minute)
       for {
           select {
               case <- c.stopChan:
                   ticker.Stop()
                   return
               case <- ticker.C:
                   ExecuteFunctionA()
           } 
       }
    }()
}

And you can invoke Stop function at the time you want to stop the ticker safely.

Upvotes: 3

Related Questions