From 31e21f690085fb8170b4ec38d6cd2c79b8eaabf3 Mon Sep 17 00:00:00 2001 From: streppel Date: Mon, 21 Sep 2020 21:21:37 -0300 Subject: [PATCH] fix: scheduler schedules jobs registration when already running (#61) * fix: scheduler schedules jobs registration when already running --- scheduler.go | 5 +++++ scheduler_test.go | 18 ++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/scheduler.go b/scheduler.go index c25d2db6..e4fd7696 100644 --- a/scheduler.go +++ b/scheduler.go @@ -392,6 +392,11 @@ func (s *Scheduler) Do(jobFun interface{}, params ...interface{}) (*Job, error) j.fparams[fname] = params j.jobFunc = fname + // we should not schedule if not running since we cant foresee how long it will take for the scheduler to start + if s.running { + s.scheduleNextRun(j) + } + return j, nil } diff --git a/scheduler_test.go b/scheduler_test.go index 27080161..c67fd701 100644 --- a/scheduler_test.go +++ b/scheduler_test.go @@ -590,3 +590,21 @@ func (f fakeTime) Sleep(duration time.Duration) { func (f fakeTime) NewTicker(duration time.Duration) *time.Ticker { panic("implement me") } + +func TestScheduler_Do(t *testing.T) { + t.Run("adding a new job before scheduler starts does not schedule job", func(t *testing.T) { + s := NewScheduler(time.UTC) + s.running = false + job, err := s.Every(1).Second().Do(func() {}) + assert.Equal(t, nil, err) + assert.True(t, job.nextRun.IsZero()) + }) + + t.Run("adding a new job when scheduler is running schedules job", func(t *testing.T) { + s := NewScheduler(time.UTC) + s.running = true + job, err := s.Every(1).Second().Do(func() {}) + assert.Equal(t, nil, err) + assert.False(t, job.nextRun.IsZero()) + }) +}