Hi all:
I am writing something as a watch-dog, for example, a timer will be reseted to timing from 0 if something happened, otherwise after a const duration, it will timeout.
To re-timing the timer, there maybe 2 ways:
tmr := time.NewTimer(d)
// watcher
for {
select {
case <- tmr.C:
// timeout! blablabla..
case <- something-happened-notice-channel:
// 2 ways to reset timer:
// tmr.Reset(d)
// tmr = time.NewTimer(d)
}
}
These 2 different ways to reset timer seems do the same thing, except the latest is more expensive because of allocating new memory and may trigger GC-handling more frequently than the 1st way, especially when a huge amount of timer is allocated (this is just what I thought, maybe incorrect, please tell me more if anyone know the details).
But when I use it in my code, these 2 ways leads my code to different result. My related function is:
func (rf *Raft) newRandTimer() {
rf.timeout = electionTimeoutGen()
/*
if rf.timer == nil {
rf.timer = time.NewTimer(rf.timeout)
} else {
rf.timer.Reset(rf.timeout)
}
*/
rf.timer = time.NewTimer(rf.timeout)
}
When I use code in /* */, it cannot reset the timer and will expired, which is not correct, however, when I code as re-allocate timer, it goes well. Any tips please?
Thanks.