Replace After With Ticker In Loops

Swap time.After for one reusable Ticker inside polling loops so per-iteration timers stop piling up before they fire.

GoResilience

Code

gosnippet
30 lines
package main

import (
	"fmt"
	"time"
)

func main() {
	deadlines := make(chan string, 3)
	go func() {
		for i := 1; i <= 3; i++ {
			deadlines <- fmt.Sprintf("task-%d done", i)
			time.Sleep(20 * time.Millisecond)
		}
	}()

	// 每轮 time.After 会新建一个定时器,未触发的要等到期才回收
	// 循环里改用单个 Ticker:复用同一个通道,Stop 一次清理
	ticker := time.NewTicker(50 * time.Millisecond)
	defer ticker.Stop()

	for i := 0; i < 3; i++ {
		select {
		case result := <-deadlines:
			fmt.Println(result)
		case <-ticker.C:
			fmt.Println("tick: still waiting")
		}
	}
}

How it works

Replace After With Ticker In Loops comes down to the function main.

A single loop drives the file — for i := 1; i <= 3; i++. Work runs on a goroutine and results come back through a channel, giving a safe handoff between the two execution contexts. Cleanup is attached with defer, so it runs on every exit path of the function.

What to watch for

  • No external packages — everything relies on the language’s built-in APIs.

Using it

Signature: func main()

Running the file prints labeled results such as tick: still waiting — each operation’s effect is visible in the output.

Key statements

deadlines <- fmt.Sprintf("task-%d done", i)
deadlines := make(chan string, 3)
defer ticker.Stop()

Interactive Tools for This Topic

FAQ

What does Replace After With Ticker In Loops print when run?
Running the file directly is enough — expect labeled output lines such as `tick: still waiting`.