Skip to content

Commit

Permalink
solve issue where job intervals drift slightly (#382)
Browse files Browse the repository at this point in the history
* solve issue where job intervals drift slightly

* golangci lint is complaining about duration Abs() method for some reason
  • Loading branch information
JohnRoesler authored Sep 7, 2022
1 parent 3272c21 commit 3867b42
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions scheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,8 @@ func (s *Scheduler) scheduleNextRun(job *Job) (bool, nextRun) {
return false, nextRun{}
}

lastRun := now

if job.neverRan() {
// Increment startAtTime to the future
if !job.startAtTime.IsZero() && job.startAtTime.Before(now) {
Expand All @@ -185,17 +187,21 @@ func (s *Scheduler) scheduleNextRun(job *Job) (bool, nextRun) {
job.startAtTime = job.startAtTime.Add(duration * count)
}
}
} else {
lastRun = job.LastRun()
}

if !job.shouldRun() {
s.RemoveByReference(job)
return false, nextRun{}
}

next := s.durationToNextRun(now, job)
next := s.durationToNextRun(lastRun, job)

job.setLastRun(job.NextRun())
if next.dateTime.IsZero() {
job.setNextRun(now.Add(next.duration))
next.dateTime = lastRun.Add(next.duration)
job.setNextRun(next.dateTime)
} else {
job.setNextRun(next.dateTime)
}
Expand Down Expand Up @@ -555,7 +561,6 @@ func (s *Scheduler) run(job *Job) {
}

s.executor.jobFunctions <- job.jobFunction.copy()
job.setLastRun(s.now())
job.runCount++
}

Expand All @@ -571,7 +576,17 @@ func (s *Scheduler) runContinuous(job *Job) {
s.run(job)
}

job.setTimer(s.timer(next.duration, func() {
nextRun := next.dateTime.Sub(s.now())
if nextRun < 0 {
time.Sleep(absDuration(nextRun))
shouldRun, next := s.scheduleNextRun(job)
if !shouldRun {
return
}
nextRun = next.dateTime.Sub(s.now())
}

job.setTimer(s.timer(nextRun, func() {
if !next.dateTime.IsZero() {
for {
n := s.now().UnixNano() - next.dateTime.UnixNano()
Expand Down

0 comments on commit 3867b42

Please sign in to comment.