英文:
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 <-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?
答案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 <-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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论