Until Computes Remaining Deadline Budget
Derive the remaining time budget from a context deadline with time.Until, and report a negative duration once the deadline has already passed.
Code
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx, cancel := context.WithDeadline(
context.Background(),
time.Now().Add(200*time.Millisecond),
)
defer cancel()
deadline, ok := ctx.Deadline()
if !ok {
panic("context has no deadline")
}
// Until = deadline - now:还没到就为正,过期后为负
fmt.Println("budget before:", time.Until(deadline).Round(time.Millisecond))
time.Sleep(220 * time.Millisecond)
fmt.Println("budget after:", time.Until(deadline).Round(time.Millisecond))
fmt.Println("ctx.Err():", ctx.Err())
}What the code does
One way to read it: the function main, doing all the work.
defer schedules the cleanup, and the scheduled call fires no matter how the function exits.
What to watch for
- The runtime is the only requirement — no packages, no install.
Applying it
Look for the budget before:, budget after:, ctx.Err(): prefixes when the file runs; they tie each line to its step.
Statements that matter
ctx, cancel := context.WithDeadline(
context.Background(),
time.Now().Add(200*time.Millisecond),
)
panic("context has no deadline")
defer cancel()
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does Until Computes Remaining Deadline Budget print when run?
- Execute the whole file; each printed line is prefixed with a label like `budget before:`, `budget after:`, `ctx.Err():`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.