go - 如何关闭定时器 channel ?

标签 go

我有一个计时器,它会因某些事件而重置。 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/

相关文章:

go - 将 GO YAML 解码为 Map 或 String

go - 如何检测 ptrace 是否已经在 golang linux 中调用

在单值上下文中使用多值

pointers - 如何将不同的错误接口(interface)实现存储在一起,然后在 Go 中使用它们进行类型比较?

go - 堆栈跟踪中的这些数字是什么意思?

mysql - 无法使用golang更新mysql中的时间戳列

go - 如何在go中多路复用 channel 输出

unit-testing - (*testing.common).Errorf 不支持错误包装指令 %w

mongodb - 在具有不同数据库的情况下在 Golang 中运行 cron

go - SIGKILL 以外的信号不会在 Windows 上终止进程