From 08a53efad778e10c5be90b33d8423e7131ed2030 Mon Sep 17 00:00:00 2001 From: Polo Ma <42830316+pma9@users.noreply.github.com> Date: Thu, 4 Aug 2022 05:08:09 -0700 Subject: [PATCH] Stops all jobs when stopping scheduler (fix #367) (#368) --- scheduler.go | 7 +++++++ scheduler_test.go | 15 +++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/scheduler.go b/scheduler.go index 6b0bd5d4..4f909ea0 100644 --- a/scheduler.go +++ b/scheduler.go @@ -813,10 +813,17 @@ func (s *Scheduler) Stop() { func (s *Scheduler) stop() { s.setRunning(false) + s.stopJobs(s.jobs) s.executor.stop() s.stopChan <- struct{}{} } +func (s *Scheduler) stopJobs(jobs []*Job) { + for _, job := range jobs { + job.stop() + } +} + func (s *Scheduler) doCommon(jobFun interface{}, params ...interface{}) (*Job, error) { job := s.getCurrentJob() diff --git a/scheduler_test.go b/scheduler_test.go index 97e4f273..833ae0bd 100644 --- a/scheduler_test.go +++ b/scheduler_test.go @@ -834,6 +834,21 @@ func TestScheduler_Stop(t *testing.T) { s.Stop() assert.False(t, s.IsRunning()) }) + t.Run("stops all jobs", func(t *testing.T) { + t.Parallel() + s := NewScheduler(time.UTC) + job, _ := s.Every(3).Second().Do(func() { + //noop + }) + s.StartAsync() + time.Sleep(1 * time.Second) // enough time for job to run + preStopJobTimer := job.timer + s.Stop() + time.Sleep(3 * time.Second) // enough time for job timer to reset + afterStopJobTimer := job.timer + + assert.Same(t, preStopJobTimer, afterStopJobTimer) + }) t.Run("waits for jobs to finish processing before returning .Stop()", func(t *testing.T) { t.Parallel() i := int32(0)