Sleep with Context

Go's standard library includes a useful function, time.Sleep, which pauses the current goroutine for at least the specified duration. This is all well and good, and commonly found in the standard libraries of many languages, but unfortunately the function is less useful in a post-context world. The problem with time.Sleep is that a goroutine should shutdown if the context cancelled, not wait for the sleep duration to expire. Additionally, callers should check the status of the context before continuing with any further work. Users really need SleepContext (perhaps SleepWithContext, or maybe context.Sleep...).

There are a few different versions on various sites, but they typically forget to return the error. It isn't difficult for callers to use the Err method on the context directly, but returning the error directly makes the necessary semantics clear.

func SleepContext

Sleep pauses the current goroutine for at least the duration d, unless the context is done. A negative or zero duration causes Sleep to return immediately.

The returned error is the same as calling ctx.Err(), and will be nil if work should continue, and non-nil if further work should be cancelled.

func SleepContext(ctx context.Context, d time.Duration) error {
	select {
	case <-ctx.Done():
		return ctx.Err()
	case <-time.After(d):
		return nil
	}
}

There is an example on the Go Playground

Join the discussion...