From e6aa452b5193d61e7d84ba9c4aae6ee6cbb20d5d Mon Sep 17 00:00:00 2001 From: Dreamacro <305009791@qq.com> Date: Mon, 13 Jul 2020 00:25:54 +0800 Subject: [PATCH] Fix: ticker leak --- adapters/provider/fetcher.go | 36 ++++++++++++++++++++++-------------- hub/route/connections.go | 1 + hub/route/server.go | 1 + 3 files changed, 24 insertions(+), 14 deletions(-) diff --git a/adapters/provider/fetcher.go b/adapters/provider/fetcher.go index 2256ff2a..3cbf5fbe 100644 --- a/adapters/provider/fetcher.go +++ b/adapters/provider/fetcher.go @@ -23,6 +23,7 @@ type fetcher struct { vehicle Vehicle updatedAt *time.Time ticker *time.Ticker + done chan struct{} hash [16]byte parser parser onUpdate func(interface{}) @@ -117,27 +118,33 @@ func (f *fetcher) Update() (interface{}, bool, error) { func (f *fetcher) Destroy() error { if f.ticker != nil { - f.ticker.Stop() + f.done <- struct{}{} } return nil } func (f *fetcher) pullLoop() { - for range f.ticker.C { - elm, same, err := f.Update() - if err != nil { - log.Warnln("[Provider] %s pull error: %s", f.Name(), err.Error()) - continue - } + for { + select { + case <-f.ticker.C: + elm, same, err := f.Update() + if err != nil { + log.Warnln("[Provider] %s pull error: %s", f.Name(), err.Error()) + continue + } - if same { - log.Debugln("[Provider] %s's proxies doesn't change", f.Name()) - continue - } + if same { + log.Debugln("[Provider] %s's proxies doesn't change", f.Name()) + continue + } - log.Infoln("[Provider] %s's proxies update", f.Name()) - if f.onUpdate != nil { - f.onUpdate(elm) + log.Infoln("[Provider] %s's proxies update", f.Name()) + if f.onUpdate != nil { + f.onUpdate(elm) + } + case <-f.done: + f.ticker.Stop() + return } } } @@ -165,6 +172,7 @@ func newFetcher(name string, interval time.Duration, vehicle Vehicle, parser par ticker: ticker, vehicle: vehicle, parser: parser, + done: make(chan struct{}, 1), onUpdate: onUpdate, } } diff --git a/hub/route/connections.go b/hub/route/connections.go index 6642b6f2..21792625 100644 --- a/hub/route/connections.go +++ b/hub/route/connections.go @@ -63,6 +63,7 @@ func getConnections(w http.ResponseWriter, r *http.Request) { } tick := time.NewTicker(time.Millisecond * time.Duration(interval)) + defer tick.Stop() for range tick.C { if err := sendSnapshot(); err != nil { break diff --git a/hub/route/server.go b/hub/route/server.go index 827cdb12..5948f121 100644 --- a/hub/route/server.go +++ b/hub/route/server.go @@ -142,6 +142,7 @@ func traffic(w http.ResponseWriter, r *http.Request) { } tick := time.NewTicker(time.Second) + defer tick.Stop() t := T.DefaultManager buf := &bytes.Buffer{} var err error