sleep.go 352 B

123456789101112131415161718192021
  1. package common
  2. import (
  3. "context"
  4. "time"
  5. )
  6. // Sleep awaits for provided interval.
  7. // Can be interrupted by context cancelation.
  8. func Sleep(ctx context.Context, interval time.Duration) error {
  9. timer := time.NewTimer(interval)
  10. select {
  11. case <-ctx.Done():
  12. if !timer.Stop() {
  13. <-timer.C
  14. }
  15. return ctx.Err()
  16. case <-timer.C:
  17. return nil
  18. }
  19. }