当引用被重新分配时,是否需要显式停止一个计时器?

huangapple go评论92阅读模式
英文:

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

问题

我正在使用time.Ticker来在固定时间间隔执行一些操作。我想要能够改变stuff发生的频率:

for {
	select {
	case <-ticker.C:
		//执行操作
	case t := <-newTicker:
		oldTicker := ticker
		ticker = t
		oldTicker.Stop()
	}
}

我需要进行ticker清理以避免内存泄漏吗?还是像下面这样重新分配ticker就足够了?

case ticker := <-newTicker:
英文:

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 &lt;-ticker.C:
			//do stuff
		case t := &lt;-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 := &lt;-newTicker:

be enough?

答案1

得分: 3

根据time包的GoDoc中JimB提到的内容,如下所述。

time.NewTicker中,提到了以下内容。

> 停止计时器以释放相关资源。

如果你运行oldTimer.Stop(),在退出case语句后,oldTicker将会被垃圾回收,因为它超出了作用域。

英文:

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.

答案2

得分: 1

使用chan time.Duration而不是chan time.Ticker,并发送一个time.Duration以供ticker的Reset()方法使用。

for {
    select {
    case <-ticker.C:
        // 执行操作
    case t := <-newTickerDuration: // (chan time.Duration)
        ticker.Reset(t)
    }
}

发送新的持续时间而不是新的ticker,并调用ticker的Reset()方法,将接收到的time.Duration传递给它。
这将停止并重置ticker的持续时间,而无需每次创建新的ticker。接受的答案确实回答了问题,但会导致增加垃圾回收并浪费资源。

英文:

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 &lt;-ticker.C:
            //do stuff
        case t := &lt;-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.

huangapple
  • 本文由 发表于 2016年11月15日 09:24:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/40600569.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定