From 221839275fbdadbfa86238793bb7616220698b64 Mon Sep 17 00:00:00 2001 From: Jordan Krage Date: Wed, 23 Oct 2024 15:56:01 -0500 Subject: [PATCH] pkg/services: add StopChan.CtxWithTimeout() (#879) --- pkg/services/stop.go | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/pkg/services/stop.go b/pkg/services/stop.go index 900ec6c84..d7f95f658 100644 --- a/pkg/services/stop.go +++ b/pkg/services/stop.go @@ -1,6 +1,9 @@ package services -import "context" +import ( + "context" + "time" +) // A StopChan signals when some work should stop. // Use StopChanR if you already have a read only <-chan. @@ -16,6 +19,11 @@ func (s StopChan) Ctx(ctx context.Context) (context.Context, context.CancelFunc) return StopRChan((<-chan struct{})(s)).Ctx(ctx) } +// CtxWithTimeout cancels a [context.Context] when StopChan is closed. +func (s StopChan) CtxWithTimeout(timeout time.Duration) (context.Context, context.CancelFunc) { + return s.CtxCancel(context.WithTimeout(context.Background(), timeout)) +} + // CtxCancel cancels a [context.Context] when StopChan is closed. // Returns ctx and cancel unmodified, for convenience. func (s StopChan) CtxCancel(ctx context.Context, cancel context.CancelFunc) (context.Context, context.CancelFunc) { @@ -36,6 +44,11 @@ func (s StopRChan) Ctx(ctx context.Context) (context.Context, context.CancelFunc return s.CtxCancel(context.WithCancel(ctx)) } +// CtxWithTimeout cancels a [context.Context] when StopChan is closed. +func (s StopRChan) CtxWithTimeout(timeout time.Duration) (context.Context, context.CancelFunc) { + return s.CtxCancel(context.WithTimeout(context.Background(), timeout)) +} + // CtxCancel cancels a [context.Context] when StopChan is closed. // Returns ctx and cancel unmodified, for convenience. func (s StopRChan) CtxCancel(ctx context.Context, cancel context.CancelFunc) (context.Context, context.CancelFunc) {