Ticker Periodic Tasks With Stop

Drive periodic maintenance with time.NewTicker, consume ticks in a select loop alongside a stop channel, and always Stop the ticker so timers do not leak.

GoResilience

Code

gosnippet
26 lines
package main

import (
	"fmt"
	"time"
)

func main() {
	// NewTicker 按固定间隔把时间值投进通道;Stop 必须调用,否则定时器泄漏
	ticker := time.NewTicker(10 * time.Millisecond)
	defer ticker.Stop()

	deadline := time.After(35 * time.Millisecond) // 模拟外部停止信号
	ticks := 0

	for {
		select {
		case <-ticker.C:
			ticks++
			fmt.Println("running maintenance, tick", ticks)
		case <-deadline:
			fmt.Println("shutting down after", ticks, "ticks")
			return
		}
	}
}

How it works

Ticker Periodic Tasks With Stop comes down to the function main.

Repetition is confined to for — the rest of the file is straight-line. defer inverts the usual order — register now, run at return — which is why cleanup cannot be skipped.

Applying it

The demo output is labeled (running maintenance, tick, shutting down after), so every printed line maps back to its originating operation.

Statements that matter

defer ticker.Stop()

Interactive Tools for This Topic

FAQ

What does Ticker Periodic Tasks With Stop print when run?
Execute the whole file; each printed line is prefixed with a label like `running maintenance, tick`, `shutting down after`.