Skip to content
This repository has been archived by the owner on Jan 28, 2021. It is now read-only.

sleep function cannot be cancelled #797

Closed
ajnavarro opened this issue Aug 7, 2019 · 4 comments · Fixed by #798
Closed

sleep function cannot be cancelled #797

ajnavarro opened this issue Aug 7, 2019 · 4 comments · Fixed by #798
Assignees
Labels
bug Something isn't working

Comments

@ajnavarro
Copy link
Contributor

we are just calling to time.Sleep, and that cannot be canceled from the Context. Change sleep to make it cancellable.

@ajnavarro ajnavarro added the bug Something isn't working label Aug 7, 2019
@juanjux
Copy link
Contributor

juanjux commented Aug 7, 2019

Easy way to reproduce: select sleep(1000) and control-C.

@creachadair
Copy link

This should do it:

// sleepContext sleeps for the specified duration or until ctx ends, and reports
// whether the sleep ended due to context cancellation.
func sleepContext(ctx context.Context, dur time.Duration) bool {
  select {
  case <-time.After(dur):
    return false
  case <-ctx.Done():
    return true
  }
}

Note that after the context ends the timer will run to completion before it will be GC'd. If that matters you can do something more explicit with time.NewTimer. But in general that is probably safe unless you start a lot of these and they run for a long time.

@juanjux
Copy link
Contributor

juanjux commented Aug 7, 2019

Already fixed, forgot to close this :)

@juanjux
Copy link
Contributor

juanjux commented Aug 7, 2019

Your solution is better since the fact that the After is of course interrupted if the ctx is Done went over me so I was dumbly doing smaller sleeps, I'm updating the PR, thanks!

@juanjux juanjux self-assigned this Aug 7, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants