英文:
golang timer re-calculate from zero
问题
我需要编写一个计时器,它可以在计时结束之前重置为零。例如,我有一个计时器:
trm := time.NewTimer(10)
如果在计时器到期之前发生了某些事件,计时器将清除所有数据,并从零重新计算,就像我重新创建一个相同的计时器一样。
我查看了Go的时间API,但没有找到相关内容。有什么建议吗?
谢谢。
英文:
I need to write a timer, which may reset itself to zero. For example, I have a
trm := time.NewTimer(10)
then, if something happened before it has expired, the timer will clear all the data it has, and re-calculate from 0, just like when I re-new a same timer.
I've checked Go's time API, and haven't found anything. Any tips?
Thanks.
答案1
得分: 3
使用time.Reset
怎么样?
Reset将计时器更改为在持续时间d之后到期。如果计时器已经处于活动状态,则返回true;如果计时器已经过期或停止,则返回false。
另一种解决方案是初始化另一个计时器。
t.Reset(x)
t := time.NewTimer(x)
除了避免垃圾回收外,它们是相同的。
一个典型的示例如下。如果经过的时间小于超时时间,则会重置计时器。
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
const timeout = 1 * time.Millisecond
t := time.NewTimer(timeout)
for {
t2 := timeout + time.Duration(rand.Intn(100)-50)*timeout/100
start := time.Now()
select {
case <-time.After(t2):
fmt.Println("Time after:", t2)
}
elapsed := time.Since(start)
if elapsed < timeout {
fmt.Println("Time ellapsed:", elapsed)
t.Reset(timeout)
}
}
}
英文:
What about to use time.Reset
?
> Reset changes the timer to expire after duration d. It returns true if
> the timer had been active, false if the timer had expired or been
> stopped.
Another solution would be to initialize another timer.
t.Reset(x)
t := time.NewTimer(x)
are identical, except for avoiding the garbage collection.
A typical example would be the following. It will reset the timer in case the elapsed time is less then the timeout.
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
const timeout = 1 * time.Millisecond
t := time.NewTimer(timeout)
for {
t2 := timeout + time.Duration(rand.Intn(100)-50)*timeout/100
start := time.Now()
select {
case <-time.After(t2):
fmt.Println("Time after:", t2)
}
elapsed := time.Since(start)
if elapsed < timeout {
fmt.Println("Time ellapsed:", elapsed)
t.Reset(timeout)
}
}
}
答案2
得分: 1
你可以使用timer.Reset
函数来重置计时器。为了重新启动计时器,将最初使用的相同持续时间作为参数传递。(在你的情况下是10
)
根据包文档:
Reset将计时器更改为在持续时间d之后到期。如果计时器之前处于活动状态,则返回true;如果计时器已经过期或已停止,则返回false。
因此,当你将相同的持续时间传递给Reset
时,计时器将从该持续时间d开始计数。这样你就有效地“续订”了计时器。
例如:
if eventHappened {
timer.Reset(10)
}
英文:
You can use timer.Reset
function, to reset the timer. To renew it, pass the same duration, you used initially as parameter. (In your case 10
)
From package documentation:
> Reset changes the timer to expire after duration d. It returns true if the timer had been active, false if the timer had expired or been stopped.
So, when you pass the same duration to Reset
, timer will start counting from that duration d. And you effectively renew
the timer.
For example:
if eventHappened {
timer.Reset(10)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论