Skip to content

Commit

Permalink
fix goroutine leaks, when using 'for range ticker.Context()' in gorou…
Browse files Browse the repository at this point in the history
…tines
  • Loading branch information
watjt committed Jul 29, 2021
1 parent 41409b4 commit 16ae185
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions pkg/ticker/ticker.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,18 @@ import (

func Context(ctx context.Context, duration time.Duration) <-chan time.Time {
ticker := time.NewTicker(duration)
c := make(chan time.Time)
go func() {
<-ctx.Done()
ticker.Stop()
for {
select {
case t := <-ticker.C:
c <- t
case <-ctx.Done():
close(c)
ticker.Stop()
return
}
}
}()
return ticker.C
return c
}

0 comments on commit 16ae185

Please sign in to comment.