Skip to content

Commit

Permalink
feat(remove/job): remove a particular job reference from the schedule…
Browse files Browse the repository at this point in the history
…r after the last execution of the job
  • Loading branch information
dlaweb committed Dec 15, 2020
1 parent 5ed8230 commit 48ec719
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
8 changes: 8 additions & 0 deletions job.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ type Job struct {
type runConfig struct {
finiteRuns bool
maxRuns int
removeAfterLastRun bool
}

// NewJob creates a new Job with the provided interval
Expand Down Expand Up @@ -147,3 +148,10 @@ func (j *Job) RunCount() int {
runCount := j.runCount
return runCount
}
// RemoveAfterLastRun update the job in order to remove the job after its last exec
func (j *Job)RemoveAfterLastRun() *Job {
j.Lock()
defer j.Unlock()
j.runConfig.removeAfterLastRun = true
return j
}
6 changes: 6 additions & 0 deletions scheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,12 @@ func (s *Scheduler) StartImmediately() *Scheduler {

// shouldRun returns true if the Job should be run now
func (s *Scheduler) shouldRun(j *Job) bool {

// option remove the job's in the scheduler after its last execution
if j.runConfig.removeAfterLastRun && (j.runConfig.maxRuns - j.runCount) == 1 {
s.RemoveByReference(j)
}

return j.shouldRun() && s.time.Now(s.loc).Unix() >= j.nextRun.Unix()
}

Expand Down
15 changes: 15 additions & 0 deletions scheduler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -881,3 +881,18 @@ func TestDo(t *testing.T) {
})
}
}

func TestRemoveAfterExec(t *testing.T) {
s := NewScheduler(time.UTC)
s.StartAsync()

job, err := s.Every(1).StartAt(time.Now().Add(1*time.Second)).Do(task, s)
require.NoError(t, err)

job.LimitRunsTo(1)
job.RemoveAfterLastRun()

time.Sleep(2 * time.Second)

assert.Zero(t, len(s.Jobs()))
}

0 comments on commit 48ec719

Please sign in to comment.