Timer Reset Rearms Idle Timeouts
Reuse one time.Timer across select iterations by stopping, draining, and resetting it, so the idle timeout renews after every event without new allocations.
Code
package main
import (
"fmt"
"time"
)
func main() {
events := make(chan string, 2)
events <- "connect"
events <- "request"
// 复用同一个 Timer:每来一个事件就重新计时,而不是每轮 time.After 新分配
idle := time.NewTimer(30 * time.Millisecond)
defer idle.Stop()
for {
select {
case ev := <-events:
fmt.Println("event:", ev)
// Stop 返回 false 表示已触发:非阻塞排空残留值再 Reset
if !idle.Stop() {
select {
case <-idle.C:
default:
}
}
idle.Reset(30 * time.Millisecond)
case <-idle.C:
fmt.Println("idle timeout: nothing within 30ms")
return
}
}
}How it works
Timer Reset Rearms Idle Timeouts keeps everything in the function main.
Repetition is confined to for — the rest of the file is straight-line. Whatever happens in the body, the defer-ed call runs last on the way out.
Using it
Running the file prints labeled results such as event:, idle timeout: nothing within 30ms — each operation’s effect is visible in the output.
Key statements
events := make(chan string, 2)
events <- "connect"
events <- "request"
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.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 Timer Reset Rearms Idle Timeouts print when run?
- Run it as a complete program — the output lines carry labels such as `event:`, `idle timeout: nothing within 30ms`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.