From 16ae185a0b20560e4f0b420cf85ba50eecbdd8db Mon Sep 17 00:00:00 2001 From: watjt <616148900@qq.com> Date: Thu, 29 Jul 2021 15:47:17 +0800 Subject: [PATCH] fix goroutine leaks, when using 'for range ticker.Context()' in goroutines --- pkg/ticker/ticker.go | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/pkg/ticker/ticker.go b/pkg/ticker/ticker.go index ec6b9d66..ebad427e 100644 --- a/pkg/ticker/ticker.go +++ b/pkg/ticker/ticker.go @@ -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 }