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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
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=`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.