WithDeadline
- Go course
- Intermediate
- Lesson 33/80
- 4 min
Learn context bound to a specific time with WithDeadline.
WithDeadline
While WithTimeout takes a relative duration, WithDeadline takes an absolute time.Time. In fact WithTimeout(ctx, d) is shorthand for WithDeadline(ctx, time.Now().Add(d)).
son := time.Date(2026, 12, 31, 23, 59, 0, 0, time.UTC)
ctx, cancel := context.WithDeadline(context.Background(), son)
defer cancel()
if d, ok := ctx.Deadline(); ok {
fmt.Println("kalan:", time.Until(d))
}Propagating the deadline
The remaining time can be read with ctx.Deadline() and adapted for subsystems. For example, gRPC and many database drivers pass the ctx deadline to the server, so when the client gives up the server stops working too. Not starting an expensive job at all when the remaining time is very short is also a good optimization.
Practice Past deadline
Pass time.Now().Add(-time.Second) to context.WithDeadline. Write defer cancel() and print ctx.Err().
Starter code
package main
import (
"context"
"fmt"
"time"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second))
defer cancel()
fmt.Println(ctx.Err())
}Expected output
context deadline exceeded
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens if <code>WithDeadline</code> is called with a date in the past?
- It is never cancelled
- It is cancelled a day later
- The context comes back already cancelled Correct answer
- It panics
Explanation: If the deadline has passed, the context is already in DeadlineExceeded; its Done channel is closed.
2 Read the deadline
if d, ok := ctx.____(); ok {
fmt.Println(time.Until(d))
}
if d, ok := ctx.Deadline(); ok {
fmt.Println(time.Until(d))
}
Explanation: Deadline returns the deadline and whether one was set.
3 Function and argument
| Term | Meaning |
|---|---|
WithTimeout |
Relative duration |
WithDeadline |
Absolute time |
ctx.Deadline() |
Deadline and ok |
time.Until(d) |
Remaining time |