Use WithTimeout for a duration and WithDeadline for a specific time to cancel Go contexts.
Use context.WithTimeout to cancel a context after a fixed duration, and context.WithDeadline to cancel it at a specific point in time.
// Cancel after 5 seconds
ctx, cancel := context.WithTimeout(parent, 5*time.Second)
defer cancel()
// Cancel at a specific time
deadline := time.Now().Add(5 * time.Second)
ctx, cancel := context.WithDeadline(parent, deadline)
defer cancel()
Think of WithTimeout as setting a timer for a specific length of time, like a microwave. WithDeadline is like setting an alarm for a specific clock time, like a meeting start time. Use the timer when you care about how long a task takes, and the alarm when you need the task to finish by a specific moment.