Using context for timeouts
A timeout is simply an automated cancellation. The context will cancel after a timer expires. This is useful in limiting resource consumption for computations that are not likely to finish.
How to do it...
These are the steps to create a context with timeout and to detect when a timeout event happens:
- Use
context.WithTimeout
to create a new cancelable context that will auto-cancel after a given duration based on an existing context and a cancellation function:ctx:=context.Background() timeoutable, cancel:=context.WithTimeout(ctx,5*time.Second) defer cancel()
Alternatively, you can use
WithDeadline
to cancel the context at a given moment.Make sure the
cancel
function is eventually called. - Pass the timeout context to computations or goroutines that can time out:
go longRunningGoroutine1(timeoutable) go longRunningGoroutine2(timeoutable)
- In the goroutine, check whether the context is canceled using the
ctx.Done()
channel orctx.Err()
:func longRunningGoroutine...