context.AfterFunc is a function for registering callback functions that execute when the context finishes.
1import "context"23func main() {4 ctx, cancel := context.WithCancel(context.Background())5 defer cancel()67 // Register callback8 stop := context.AfterFunc(ctx, func() {9 fmt.Println("Context cancelled, cleaning up...")10 cleanupResources()11 })1213 // Start work14 go doWork(ctx)1516 // Stop after 5 seconds17 time.Sleep(5 * time.Second)18 cancel() // Will trigger callback!1920 // stop() — cancels callback registration21 // if context hasn't finished yet22}2324// Example: timeout with cleanup25func processWithTimeout(ctx context.Context) error {26 ctx, cancel := context.WithTimeout(ctx, 10*time.Second)27 defer cancel()2829 // Cleanup on cancellation30 stop := context.AfterFunc(ctx, func() {31 log.Println("Request cancelled, releasing resources")32 releaseLock()33 })34 defer stop() // Cancel callback if everything is fine3536 return doWork(ctx)37}3839// Example: goroutine pool40func startPool(ctx context.Context, workers int) {41 context.AfterFunc(ctx, func() {42 fmt.Println("Stopping all workers...")43 // Stopping workers44 })4546 for i := 0; i < workers; i++ {47 go worker(ctx)48 }49}
When to use: