Senior
Kas saaksite anda näiteid WithCancel, WithTimeout ja WithDeadline kasutamisest?
sobes.tech AI
Vastus AI-lt
In the context package of Go, there are functions to create contexts with the ability to cancel and set execution time limits:
-
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 duration.
-
WithDeadline — creates a context that cancels at a specific time.
Examples:
ctx, cancel := context.WithCancel(context.Background())
// Start a goroutine that will cancel 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 managing resources.