From 9112e78925925bd343b53a643fb20be697700536 Mon Sep 17 00:00:00 2001 From: Joe Tsai Date: Mon, 6 Mar 2023 17:40:38 -0800 Subject: [PATCH] tstime: add Sleep (#7480) Sleep is an interruptible sleep variation. Signed-off-by: Joe Tsai --- tstime/tstime.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/tstime/tstime.go b/tstime/tstime.go index 9ad4ec76e..cb3b467e6 100644 --- a/tstime/tstime.go +++ b/tstime/tstime.go @@ -5,6 +5,7 @@ package tstime import ( + "context" "errors" "fmt" "strconv" @@ -164,3 +165,16 @@ func ParseDuration(s string) (time.Duration, error) { } return time.ParseDuration(s) } + +// Sleep is like [time.Sleep] but returns early upon context cancelation. +// It reports whether the full sleep duration was achieved. +func Sleep(ctx context.Context, d time.Duration) bool { + timer := time.NewTimer(d) + defer timer.Stop() + select { + case <-ctx.Done(): + return false + case <-timer.C: + return true + } +}