Skip to content

Commit

Permalink
add mutex to job (#74)
Browse files Browse the repository at this point in the history
* add mutex to job

* go vet
  • Loading branch information
JohnRoesler committed Nov 10, 2020
1 parent daf5304 commit 0969260
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 5 deletions.
6 changes: 5 additions & 1 deletion job.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
}

Expand Down
2 changes: 2 additions & 0 deletions scheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
8 changes: 4 additions & 4 deletions scheduler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 0969260

Please sign in to comment.