diff --git a/api/scheduler/scheduler.go b/api/scheduler/scheduler.go index d779175b5..e391ae6d2 100644 --- a/api/scheduler/scheduler.go +++ b/api/scheduler/scheduler.go @@ -94,7 +94,12 @@ func (s *Scheduler) StopJob(jobID string) error { // Returns job id that could be used to stop the given job. // When job run returns an error, that job won't be run again. func (s *Scheduler) StartJobEvery(duration time.Duration, job func() error) string { - ctx, cancel := context.WithCancel(context.Background()) + entryID := new(cron.EntryID) + + cancelFn := func() { + log.Debug().Msg("job cancelled, stopping") + s.crontab.Remove(*entryID) + } jobFn := cron.FuncJob(func() { err := job() @@ -105,7 +110,7 @@ func (s *Scheduler) StartJobEvery(duration time.Duration, job func() error) stri var permErr *PermanentError if errors.As(err, &permErr) { log.Error().Err(permErr).Msg("job returned a permanent error, it will be stopped") - cancel() + cancelFn() return } @@ -113,17 +118,11 @@ func (s *Scheduler) StartJobEvery(duration time.Duration, job func() error) stri log.Error().Err(err).Msg("job returned an error, it will be rescheduled") }) - entryID := s.crontab.Schedule(cron.Every(duration), jobFn) + *entryID = s.crontab.Schedule(cron.Every(duration), jobFn) s.mu.Lock() - s.activeJobs[entryID] = cancel + s.activeJobs[*entryID] = cancelFn s.mu.Unlock() - go func(entryID cron.EntryID) { - <-ctx.Done() - log.Debug().Msg("job cancelled, stopping") - s.crontab.Remove(entryID) - }(entryID) - - return strconv.Itoa(int(entryID)) + return strconv.Itoa(int(*entryID)) }