← 中文资源

简体中文版本

安全停止并排空 time.Timer 通道

在调用 Reset 重置 time.Timer 之前先检查 Stop 返回值,并用非阻塞 select 排空已过期定时器可能残留的通道信号。

阅读英文原文

实现说明

安全停止并排空 time.Timer 通道的核心是函数 resetSafely、main。 defer 预约了清理,无论函数怎么退出,预约的调用都会触发。

使用要点

  • 没有引入任何第三方内容;示例无依赖。
  • 跑完文件,输出里会留下标记——stopped active timer early:、expired early=。
  • main 的演示流程是 resetSafely——跑一遍文件,这条流程从头到尾可见。

常见问题

运行「安全停止并排空 time.Timer 通道」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 stopped active timer early:、expired early= 标签标明各步骤。

主签名形如 func resetSafely(t *time.Timer, d time.Duration) (stoppedEarly bool)

核心语句

func resetSafely(t *time.Timer, d time.Duration) (stoppedEarly bool) {
	stoppedEarly = t.Stop()
	if !stoppedEarly {
		// Non-blocking drain handles stale ticks on Go <=1.22 and stays safe on Go 1.23+
		select {
		case <-t.C:
		default:
		}
	}
	t.Reset(d)
	return stoppedEarly
}
defer timer.Stop()

代码示例

package main

import (
	"fmt"
	"time"
)

func resetSafely(t *time.Timer, d time.Duration) (stoppedEarly bool) {
	stoppedEarly = t.Stop()
	if !stoppedEarly {
		// Non-blocking drain handles stale ticks on Go <=1.22 and stays safe on Go 1.23+
		select {
		case <-t.C:
		default:
		}
	}
	t.Reset(d)
	return stoppedEarly
}

func main() {
	timer := time.NewTimer(80 * time.Millisecond)
	defer timer.Stop()

	// Case 1: stop before firing, then reset to 5ms
	early1 := resetSafely(timer, 5*time.Millisecond)
	fmt.Println("stopped active timer early:", early1)

	// Case 2: let timer expire without reading timer.C, then drain & reset
	time.Sleep(35 * time.Millisecond)
	start := time.Now()
	early2 := resetSafely(timer, 30*time.Millisecond)
	<-timer.C
	fmt.Printf("expired early=%t, rearmed elapsed>=15ms=%t\n",
		early2, time.Since(start) >= 15*time.Millisecond)
}