Ticker Reset Adapts Polling Interval

time.Ticker.Reset changes the interval between ticks, so a poller can start fast and back off to slower cadence without rebuilding the timer.

GoResilience

Code

gosnippet
28 lines
package main

import (
	"fmt"
	"time"
)

func main() {
	// adaptive polling: Reset adapts the interval between ticks
	ticker := time.NewTicker(30 * time.Millisecond)
	defer ticker.Stop()

	deadline := time.After(250 * time.Millisecond)
	polls := 0
	for {
		select {
		case <-ticker.C:
			polls++
			if polls == 1 {
				ticker.Reset(120 * time.Millisecond) // idle workload: slower polling cadence
			}
			fmt.Println("poll", polls)
		case <-deadline:
			fmt.Println("stopped after", polls, "polls")
			return
		}
	}
}

What the code does

The compressed view: all the work sits in the function main, doing all the work.

One loop does the cycling here: for. defer schedules the cleanup, and the scheduled call fires no matter how the function exits.

What to watch for

  • The runtime alone is required here — no packages, no install step.

Applying it

The file’s steps are announced right in the output: poll, stopped after.

Statements that carry the weight

defer ticker.Stop()

Interactive Tools for This Topic

FAQ

What does Ticker Reset Adapts Polling Interval print when run?
No setup needed: run the file and look for labeled lines like `poll`, `stopped after` in the output.