From c5686c488483c42e5c75e48e70ca875c13f40d73 Mon Sep 17 00:00:00 2001 From: Deluan Date: Sun, 31 Jan 2021 17:37:54 -0500 Subject: [PATCH] Replace periodic scanner cancellation channel with a context --- cmd/root.go | 10 +++++----- scanner/scanner.go | 17 +++++------------ 2 files changed, 10 insertions(+), 17 deletions(-) diff --git a/cmd/root.go b/cmd/root.go index 6954c1925..6be877b36 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -1,6 +1,7 @@ package cmd import ( + "context" "fmt" "os" "time" @@ -79,21 +80,20 @@ func startScanner() (func() error, func(err error)) { interval := conf.Server.ScanInterval log.Info("Starting scanner", "interval", interval.String()) scanner := GetScanner() - done := make(chan struct{}) + ctx, cancel := context.WithCancel(context.Background()) return func() error { if interval != 0 { time.Sleep(2 * time.Second) // Wait 2 seconds before the first scan - scanner.Start(interval) + scanner.Run(ctx, interval) } else { log.Warn("Periodic scan is DISABLED", "interval", interval) + <-ctx.Done() } - <-done return nil }, func(err error) { - scanner.Stop() - done <- struct{}{} + cancel() if err != nil { log.Error("Shutting down Scanner due to error", err) } else { diff --git a/scanner/scanner.go b/scanner/scanner.go index db6f7616d..dac9bfe13 100644 --- a/scanner/scanner.go +++ b/scanner/scanner.go @@ -16,8 +16,7 @@ import ( ) type Scanner interface { - Start(interval time.Duration) - Stop() + Run(ctx context.Context, interval time.Duration) RescanAll(ctx context.Context, fullRescan bool) error Status(mediaFolder string) (*StatusInfo, error) Scanning() bool @@ -49,7 +48,6 @@ type scanner struct { ds model.DataStore cacheWarmer core.CacheWarmer broker events.Broker - done chan bool scan chan bool } @@ -68,34 +66,29 @@ func New(ds model.DataStore, cacheWarmer core.CacheWarmer, broker events.Broker) folders: map[string]FolderScanner{}, status: map[string]*scanStatus{}, lock: &sync.RWMutex{}, - done: make(chan bool), scan: make(chan bool), } s.loadFolders() return s } -func (s *scanner) Start(interval time.Duration) { +func (s *scanner) Run(ctx context.Context, interval time.Duration) { ticker := time.NewTicker(interval) defer ticker.Stop() for { - err := s.RescanAll(context.Background(), false) + err := s.RescanAll(ctx, false) if err != nil { log.Error(err) } select { case <-ticker.C: continue - case <-s.done: + case <-ctx.Done(): return } } } -func (s *scanner) Stop() { - s.done <- true -} - func (s *scanner) rescan(ctx context.Context, mediaFolder string, fullRescan bool) error { folderScanner := s.folders[mediaFolder] start := time.Now() @@ -163,7 +156,7 @@ func (s *scanner) RescanAll(ctx context.Context, fullRescan bool) error { isScanning.Set(true) defer isScanning.Set(false) - defer s.cacheWarmer.Flush(context.Background()) + defer s.cacheWarmer.Flush(ctx) var hasError bool for folder := range s.folders { err := s.rescan(ctx, folder, fullRescan)