Senior
Can you provide examples of using WithCancel, WithTimeout, and WithDeadline?
sobes.tech AI
Answer from AI
In the Go package context, there are functions for creating contexts with cancellation and timeout capabilities:
-
WithCancel — creates a context that can be manually canceled by calling the cancel() function. Used when you need to interrupt an operation upon an event.
-
WithTimeout — creates a context that automatically cancels after a specified period.
-
WithDeadline — creates a context that cancels at a specific point in time.
Examples:
ctx, cancel := context.WithCancel(context.Background())
// Launch a goroutine that cancels the context after 2 seconds
go func() {
time.Sleep(2 * time.Second)
cancel()
}()
select {
case <-ctx.Done():
fmt.Println("Operation canceled")
}
// WithTimeout
ctxTimeout, cancelTimeout := context.WithTimeout(context.Background(), 3*time.Second)
defer cancelTimeout()
// operation that will be interrupted after 3 seconds
// WithDeadline
deadline := time.Now().Add(5 * time.Second)
ctxDeadline, cancelDeadline := context.WithDeadline(context.Background(), deadline)
defer cancelDeadline()
// operation that will be interrupted at the specified time
These mechanisms are useful for controlling request execution time, canceling long operations, and resource management.