我有一个计时器,它会因某些事件而重置。 go 函数使用 range 监听 channel 。如何关闭 channel 以便 for 循环退出?
func resetTimer(){
if rf.electionTimer != nil {
rf.electionTimer.Stop()
}
}
rf.electionTimer = time.NewTimer(electionTime)
for _ = range rf.electionTimer.C {
// Do something
}
最佳答案
使用 channel 来发出循环何时应退出的信号。
rf.done := make(chan struct{})
rf.electionTimer = time.NewTimer(electionTime)
func stopTimer(){
if rf.electionTimer != nil {
rf.electionTimer.Stop()
close(rf.done)
}
}
循环选择信号 channel 和定时器 channel 。当信号 channel 关闭时跳出循环。
loop:
for {
select {
case t := <-rf.electionTimer.C:
// Do something
case <-rf.done:
break loop
}
}
请注意,如果应用程序不调用Reset,则在问题或此答案中使用循环是没有意义的。在计时器上。如果定时器没有重置,那么只有一个值将被发送到定时器的 channel 。
关于go - 如何关闭定时器 channel ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47647333/