Skip to content

Commit

Permalink
Cleanup goroutines on health.Stop (#1325)
Browse files Browse the repository at this point in the history
  • Loading branch information
StephenButtolph authored Apr 11, 2023
1 parent 9cf116b commit 4a7ad6a
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
5 changes: 5 additions & 0 deletions api/health/health.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,12 @@ type Health interface {
Registerer
Reporter

// Start running periodic health checks at the specified frequency.
// Repeated calls to Start will be no-ops.
Start(ctx context.Context, freq time.Duration)

// Stop running periodic health checks. Stop should only be called after
// Start. Once Stop returns, no more health checks will be executed.
Stop()
}

Expand Down
8 changes: 7 additions & 1 deletion api/health/worker.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ type worker struct {

startOnce sync.Once
closeOnce sync.Once
wg sync.WaitGroup
closer chan struct{}
}

Expand Down Expand Up @@ -126,9 +127,13 @@ func (w *worker) Results(tags ...string) (map[string]Result, bool) {
func (w *worker) Start(ctx context.Context, freq time.Duration) {
w.startOnce.Do(func() {
detachedCtx := utils.Detach(ctx)
w.wg.Add(1)
go func() {
ticker := time.NewTicker(freq)
defer ticker.Stop()
defer func() {
ticker.Stop()
w.wg.Done()
}()

w.runChecks(detachedCtx)
for {
Expand All @@ -146,6 +151,7 @@ func (w *worker) Start(ctx context.Context, freq time.Duration) {
func (w *worker) Stop() {
w.closeOnce.Do(func() {
close(w.closer)
w.wg.Wait()
})
}

Expand Down

0 comments on commit 4a7ad6a

Please sign in to comment.