Stop And Safely Drain A time.Timer

Stop an active or expired time.Timer and drain its channel with a non-blocking select before Reset so stale ticks never fire early.

GoResilience

Code

snippet
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)
}

Code mechanics — Stop And Safely Drain A time.Timer

Stop And Safely Drain A time.Timer keeps everything in the functions resetSafely and main.

defer schedules the cleanup, and the scheduled call fires no matter how the function exits.

What to watch for

  • Nothing third-party is pulled in; the snippet is dependency-free.

Putting it to use

Entry signature: func resetSafely(t *time.Timer, d time.Duration) (stoppedEarly bool)

Output lines are prefixed (stopped active timer early:, expired early=), clarifying which execution phase produced every terminal row.

The entry point wires resetSafely together — run it once and the whole demo flows.

Core lines

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()

Interactive Tools for This Topic

FAQ

What does Stop And Safely Drain A time.Timer print when run?
The script runs standalone; its 2 labeled outputs include `stopped active timer early:`, `expired early=`.