Context AfterFunc Registers Cleanup On Done
Register cleanup with context.AfterFunc so a canceled context triggers it in its own goroutine, and stop cancels the registration before the context ends.
Code
package main
import (
"context"
"fmt"
"time"
)
func main() {
// 路径一:ctx 被取消,注册的清理回调被触发
ctxA, cancelA := context.WithCancel(context.Background())
firedA := make(chan struct{})
doneA := context.AfterFunc(ctxA, func() {
fmt.Println("cleanup ran for A")
close(firedA)
})
fmt.Println("A registered:", doneA != nil)
cancelA()
<-firedA // 确认回调已执行
fmt.Println("A stop after fired returns:", doneA())
// 路径二:在 ctx 结束前 stop(),回调永远不会执行
ctxB, cancelB := context.WithCancel(context.Background())
stopB := context.AfterFunc(ctxB, func() {
fmt.Println("cleanup ran for B")
})
fmt.Println("B stop before done returns:", stopB())
cancelB()
time.Sleep(10 * time.Millisecond)
fmt.Println("B produced no cleanup output above")
}Inside the snippet
Context AfterFunc Registers Cleanup On Done is built around the function main.
What to watch for
- Any imports it does have stop at the standard-library modules.
Using it
The demo output is labeled (cleanup ran for A, A registered:, A stop after fired returns:), so the output doubles as a step-by-step trace of what the file did.
The key statements, annotated
doneA := context.AfterFunc(ctxA, func() {
fmt.Println("cleanup ran for A")
close(firedA)
})
stopB := context.AfterFunc(ctxB, func() {
fmt.Println("cleanup ran for B")
})
firedA := make(chan struct{})
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.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 Context AfterFunc Registers Cleanup On Done print when run?
- Run it as a complete program — the output lines carry labels such as `cleanup ran for A`, `A registered:`, `A stop after fired returns:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.