How to Use context.AfterFunc (Go 1.21+)

Schedule a function to run after a duration or context cancellation using context.AfterFunc in Go 1.21+.

Use context.AfterFunc to schedule a function to run after a specified duration or when a context is cancelled, whichever happens first.

ctx, cancel := context.WithCancel(context.Background())

// Schedule cleanup to run when ctx is cancelled.
stop := context.AfterFunc(ctx, func() {
    fmt.Println("Cleanup executed")
})

// Later, cancel the context to trigger the function:
cancel()

// Or call stop() to prevent the function from running:
// stopped := stop()