Go core
Browse topics

context.WithTimeout and WithDeadline

Version
1.27
Since
1.7
Review
Draft

Summary#

context.WithTimeout creates a child context with a deadline relative to the current time. WithDeadline takes an absolute time. A child cannot extend an earlier parent deadline. When the deadline ends the context, Err returns context.DeadlineExceeded. Explicit cancellation can end it sooner.

Syntax#

go
timeoutCtx, cancelTimeout := context.WithTimeout(parent, 2*time.Second)
defer cancelTimeout()

deadlineCtx, cancelDeadline := context.WithDeadline(parent, deadline)
defer cancelDeadline()

Example#

go
package main

import (
	"context"
	"errors"
	"fmt"
	"time"
)

func wait(ctx context.Context, work <-chan struct{}) error {
	select {
	case <-work:
		return nil
	case <-ctx.Done():
		return ctx.Err()
	}
}

func main() {
	parent, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
	defer cancel()

	child, cancelChild := context.WithDeadline(parent, time.Now().Add(time.Hour))
	defer cancelChild()

	parentDeadline, _ := parent.Deadline()
	childDeadline, _ := child.Deadline()
	fmt.Println(childDeadline.Equal(parentDeadline))

	neverReady := make(chan struct{})
	err := wait(child, neverReady)
	fmt.Println(err)
	fmt.Println(errors.Is(err, context.DeadlineExceeded))
}

Expected output#

Text
true
context deadline exceeded
true

Common mistakes#

context deadline exceeded is the message of context.DeadlineExceeded: the deadline passed before the operation finished. Test for it with errors.Is, because packages such as net/http wrap it. Check that the timeout covers the slowest expected response and that a parent context does not set an earlier deadline.

Call cancel even when the timeout will expire on its own, so resources are released as soon as the work finishes. A deadline stops nothing by itself: the operation must accept the context or watch Done.

Version applicability#

The standard context package arrived in Go 1.7. The complete example requires Go 1.13 for errors.Is. With Go 1.21's WithTimeoutCause and WithDeadlineCause, context.Cause can return a supplied error when the deadline expires.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0