Below code:
// Sample program to show how to use the WithDeadline function
// of the Context package.
package main
import (
"context"
"fmt"
"time"
)
type data struct {
UserID string
}
func main() {
// Set a duration.
// duration := 150 * time.Millisecond
duration := time.Now().Add(3 * time.Second)
// Create a context that is both manually cancellable and will signal
// a cancel at the specified duration.
ctx, cancel := context.WithDeadline(context.Background(), duration)
defer cancel()
// Create a channel to received a signal that work is done.
ch := make(chan data, 1)
// Ask the goroutine to do some work for us.
go func() {
// Simulate work.
time.Sleep(50 * time.Millisecond)
// Report the work is done.
ch <- data{"123"}
}()
// Wait for the work to finish. If it takes too long move on.
select {
case d := <-ch:
fmt.Println("work complete", d)
case <-ctx.Done():
fmt.Println("work cancelled")
}
}
is using WithDeadline for sending timer'd cancel(). This can be done using:
duration := 150 * time.Millisecond
// Create a context that is both manually cancellable and will signal
// a cancel at the specified duration.
ctx, cancel := context.WithTimeout(context.Background(), duration)
Internally, context.WithTimeout calls the context.WithDeadline function and generates the deadline by adding timeout to the current time.
How is context.WithTimeout() different from context.WithDeadline()?
WithTimeout is a convenience function for executing WithDeadline(parent, time.Now().Add(timeout)).
The functions differ in how the application specifies the deadline. Otherwise they are the same.
Call the function appropriate for the value you have on hand.
How context.WithTimeout() different from context.WithDeadline()
The first takes a duration after which to cancel from now, the second an absolute time to call cancel as explained in the documentation which is worth reading as usual.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With