Skip to content

Commit 4f2c57a

Browse files
committed
pkg/services: add Engine.GoTickUntil & Engine.WaitFor
1 parent df4dc2a commit 4f2c57a

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

pkg/services/service.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,36 @@ func (e *Engine) GoTick(ticker *timeutil.Ticker, fn func(context.Context)) {
107107
})
108108
}
109109

110+
// GoTickUntil is like GoTick but halts when fn returns true, and closes the returned chan.
111+
func (e *Engine) GoTickUntil(ticker *timeutil.Ticker, fn func(context.Context) bool) <-chan struct{} {
112+
ch := make(chan struct{})
113+
e.Go(func(ctx context.Context) {
114+
defer ticker.Stop()
115+
for {
116+
select {
117+
case <-ctx.Done():
118+
return
119+
case <-ticker.C:
120+
if fn(ctx) {
121+
close(ch)
122+
return
123+
}
124+
}
125+
}
126+
})
127+
return ch
128+
}
129+
130+
// WaitFor blocks on receiving from ch then return true, or exits early if the Engine is closed and returns false.
131+
func (e *Engine) WaitFor(ch <-chan struct{}) bool {
132+
select {
133+
case <-e.StopChan:
134+
return false
135+
case <-ch:
136+
}
137+
return true
138+
}
139+
110140
// Tracer returns the otel tracer with service attributes included.
111141
func (e *Engine) Tracer() trace.Tracer {
112142
return e.tracer

0 commit comments

Comments
 (0)