Go Reference ยท Concurrency and Context
Go context.WithTimeout() and WithDeadline()
Reference for Go context.WithTimeout and context.WithDeadline: derive a context that expires after a duration or at a time, DeadlineExceeded, and cancel rules.
context.WithTimeout derives a child context that is cancelled automatically after a duration. context.WithDeadline does the same at an absolute point in time. When the time is up, the child's Done channel closes and Err() returns context.DeadlineExceeded.
WithTimeout(parent, d) is simply WithDeadline(parent, time.Now().Add(d)). Both also return a cancel function that releases the timer early; call it as soon as the work is done.
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel()
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) func WithTimeoutCause(parent Context, timeout time.Duration, cause error) (Context, CancelFunc) func WithDeadlineCause(parent Context, d time.Time, cause error) (Context, CancelFunc)
| Name | Description |
|---|---|
parent |
Context to derive from. |
timeout |
How long the child may live, measured from the call. |
d |
The absolute time at which the child expires. |
cause |
Error returned by context.Cause when the deadline fires (Go 1.21). |
Returns. The child context and a CancelFunc. ctx.Deadline() reports the effective deadline.
Edge cases.
- If the parent already has an earlier deadline, the child simply uses it; deadlines can only get shorter down a chain.
- A zero or negative timeout, or a deadline in the past, produces a context that is already expired.
ctx.Err()iscontext.DeadlineExceededfor expiry andcontext.Canceledifcancel(or the parent) ran first. The text ofDeadlineExceededis "context deadline exceeded".
Usage notes
- Call
cancel, normally withdefer cancel(). A timeout context holds a timer until it fires or is cancelled; skippingcancelwastes resources andgo vetreports it. - Timeouts need cooperation. The context only signals. Your code must select on
ctx.Done()or use APIs that take a context:http.NewRequestWithContext,db.QueryContext,exec.CommandContext,net.Dialer.DialContext. - Pick the deadline at the edge. Set one per incoming request or job and pass the context down, rather than adding a new timeout at every layer.
- Check remaining time with
ctx.Deadline()andtime.Until(deadline)before starting work that cannot finish in time. DeadlineExceededsatisfiesnet.ErrorwithTimeout() == true, so generic timeout checks work.- Per-attempt limits: when retrying, derive a fresh
WithTimeoutfor each attempt from the overall context.