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.
Code
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
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 AfterFunc Schedules One-Shot Timers print when run?
- The script runs standalone; its 2 labeled outputs include `one-shot callback fired`, `stop after firing:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.