In the context package a Sleep(Context, time.Duration) function would be useful as a tool to migrate code that uses time.Sleep to be aware of context cancellation.
// before
time.Sleep(1*time.Second)
// after
context.Sleep(ctx, 1*time.Second)
Why add it to the stdlib:
context is the place users should expect such toolHere is a naive implementation:
func Sleep(ctx context.Context, delay time.Duration) {
timeoutCtx, cancel := context.WithTimeout(ctx, delay)
defer cancel()
<-timeoutCtx.Done()
}
I'm not sure if I follow. You're arguing that people should be able to write
context.Sleep(ctx, time.Second)
However, they could pretty easily just write:
select {
case <-time.After(time.Second):
case <-ctx.Done():
// probably early return here
}
You can argue that the select is more lines, but I would argue that you need them anyway, because the code should handle context cancellation by stopping work instead of continuing as normal.
A pure Sleep function without return value isn't that useful.
A more useful signature would return a boolean telling if the timeout has been reached or if the context has been canceled. In that case the name Sleep is not appropriate as the signature doesn't match time.Sleep. So this is not the right proposal.
So, closed.
Most helpful comment
I'm not sure if I follow. You're arguing that people should be able to write
However, they could pretty easily just write:
You can argue that the select is more lines, but I would argue that you need them anyway, because the code should handle context cancellation by stopping work instead of continuing as normal.