AfterFunc Schedules One-Shot Timers

Schedule a one-shot callback on its own goroutine with time.AfterFunc, then observe that Stop on an already-fired timer reports false instead of cancelling.

GoResilience

Code

gosnippet
24 lines
package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {
	var wg sync.WaitGroup

	// AfterFunc 在延迟到期后,于自己的 goroutine 里运行回调
	wg.Add(1)
	timer := time.AfterFunc(30*time.Millisecond, func() {
		fmt.Println("one-shot callback fired")
		wg.Done()
	})

	// 让回调跑完;对已触发的 timer 调 Stop 返回 false
	time.Sleep(50 * time.Millisecond)
	fmt.Println("stop after firing:", timer.Stop())

	wg.Wait()
}

How the code behaves

AfterFunc Schedules One-Shot Timers comes down to the function main.

What to watch for

  • Nothing outside the runtime — the calls land on the language’s own APIs.

Using it

Signature: func main()

The demo output is labeled (one-shot callback fired, stop after firing:), so each printed line points back to the step that produced it.

Lines that carry the behavior

var wg sync.WaitGroup

Interactive Tools for This Topic

FAQ

What does AfterFunc Schedules One-Shot Timers print when run?
The script runs standalone; its 2 labeled outputs include `one-shot callback fired`, `stop after firing:`.