diff --git a/job.go b/job.go index 65f5bddb..9a9bca5c 100644 --- a/job.go +++ b/job.go @@ -2,11 +2,13 @@ package gocron import ( "fmt" + "sync" "time" ) // Job struct stores the information necessary to run a Job type Job struct { + sync.RWMutex interval uint64 // pause interval * unit between runs unit timeUnit // time units, ,e.g. 'minutes', 'hours'... startsImmediately bool // if the Job should run upon scheduler start @@ -44,11 +46,13 @@ func NewJob(interval uint64) *Job { // Run the Job and immediately reschedule it func (j *Job) run() { + j.Lock() + defer j.Unlock() callJobFuncWithParams(j.funcs[j.jobFunc], j.fparams[j.jobFunc]) j.runCount++ } -func (j Job) neverRan() bool { +func (j *Job) neverRan() bool { return j.lastRun.IsZero() } diff --git a/scheduler.go b/scheduler.go index f1e80b2f..eeefabc3 100644 --- a/scheduler.go +++ b/scheduler.go @@ -88,6 +88,8 @@ func (s *Scheduler) ChangeLocation(newLocation *time.Location) { // scheduleNextRun Compute the instant when this Job should run next func (s *Scheduler) scheduleNextRun(j *Job) { + j.Lock() + defer j.Unlock() now := s.time.Now(s.loc) if j.startsImmediately { diff --git a/scheduler_test.go b/scheduler_test.go index c67fd701..b961597d 100644 --- a/scheduler_test.go +++ b/scheduler_test.go @@ -252,17 +252,17 @@ func TestSwap(t *testing.T) { s.Every(2).Minute().Do(task) jb := s.Jobs() - var jobsBefore []Job + var jobsBefore []*Job for _, p := range jb { - jobsBefore = append(jobsBefore, *p) + jobsBefore = append(jobsBefore, p) } s.Swap(1, 0) jobsAfter := s.Jobs() - assert.Equal(t, &jobsBefore[0], jobsAfter[1]) - assert.Equal(t, &jobsBefore[1], jobsAfter[0]) + assert.Equal(t, jobsBefore[0], jobsAfter[1]) + assert.Equal(t, jobsBefore[1], jobsAfter[0]) } func TestLess(t *testing.T) {