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()