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.
Code
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
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 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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.