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.

GoResilience

Code

gosnippet
34 lines
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

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`.