diff --git a/nowplaying.go b/nowplaying.go index 2b6d534..2722ea8 100644 --- a/nowplaying.go +++ b/nowplaying.go @@ -63,6 +63,10 @@ type nowPlayingService struct { snapshot NowPlayingSnapshot fetchedAt time.Time lastError string + + startOnce sync.Once + stopPoll context.CancelFunc + pollDone chan struct{} } func newNowPlayingService(settings *settingsStore, logger *log.Logger, playlists ...*playlistStore) *nowPlayingService { @@ -90,22 +94,41 @@ func newNowPlayingService(settings *settingsStore, logger *log.Logger, playlists } func (s *nowPlayingService) Start() { - go func() { - for { - settings := s.settings.Get() - wait := time.Duration(settings.AzuraCast.PollSeconds) * time.Second - if wait < 5*time.Second { - wait = 15 * time.Second + s.startOnce.Do(func() { + ctx, cancel := context.WithCancel(context.Background()) + s.stopPoll = cancel + s.pollDone = make(chan struct{}) + go func() { + defer close(s.pollDone) + for { + if ctx.Err() != nil { return } + settings := s.settings.Get() + wait := time.Duration(settings.AzuraCast.PollSeconds) * time.Second + if wait < 5*time.Second {wait = 15*time.Second} + requestCtx, stop := context.WithTimeout(ctx, 12*time.Second) + _, err := s.Get(requestCtx, false) + stop() + if err != nil && wait > 5*time.Second {wait = 5*time.Second} + timer := time.NewTimer(wait) + select { + case <-ctx.Done(): + timer.Stop() + return + case <-timer.C: + } } - ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second) - _, err := s.Get(ctx, false) - cancel() - if err != nil && wait > 5*time.Second { - wait = 5 * time.Second - } - time.Sleep(wait) - } - }() + }() + }) +} + +// Stop cancels the background poller during graceful server shutdown. +func (s *nowPlayingService) Stop(ctx context.Context) { + if s == nil || s.stopPoll == nil {return} + s.stopPoll() + select { + case <-s.pollDone: + case <-ctx.Done(): + } } func (s *nowPlayingService) Current() NowPlayingSnapshot {