Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add mutex to job #74

Merged
merged 2 commits into from
Nov 10, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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