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.

GoResilience

Code

snippet
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

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():`.