July 2019
Intermediate to advanced
458 pages
12h 12m
English
context.WithDeadline is another decorator, which specifies a time deadline as time.Time, and applies it to another context. If there is already a deadline and it is earlier than the one provided, the specified one gets ignored. If the done channel is still open when the deadline is met, it gets closed automatically.
In the following example, we set the deadline to be 5 seconds from now and call cancel 10 seconds after. The deadline arrives before the cancellation and Err returns a context.DeadlineExceeded error:
func main() { ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(5*time.Second)) time.AfterFunc(time.Second*10, cancel) done := ctx.Done() for i := 0; ; i++ { select { case <-done: fmt.Println("exit", ...Read now
Unlock full access