2024-02-17 03:48:29 +00:00
|
|
|
// SPDX-License-Identifier: BSD-3-Clause
|
2020-09-03 23:01:53 +03:00
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Sleep awaits for provided interval.
|
2024-04-12 15:00:55 +08:00
|
|
|
// Can be interrupted by context cancellation.
|
2020-09-03 23:01:53 +03:00
|
|
|
func Sleep(ctx context.Context, interval time.Duration) error {
|
2021-12-22 21:54:41 +00:00
|
|
|
timer := time.NewTimer(interval)
|
2020-09-03 23:01:53 +03:00
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
2023-05-28 12:32:10 +00:00
|
|
|
if !timer.Stop() {
|
|
|
|
<-timer.C
|
|
|
|
}
|
2020-09-03 23:01:53 +03:00
|
|
|
return ctx.Err()
|
|
|
|
case <-timer.C:
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|