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 14, 2020
1 parent 5ed8230 commit 6ed05ca
Show file tree
Hide file tree
Showing 3 changed files with 39 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
toRemove 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
}
// RemoveAfterLastExec set a toRemove parameter in order to remove the job afer its last exec
func (j *Job)RemoveAfterLastExec() *Job {
j.Lock()
defer j.Unlock()
j.runConfig.toRemove = true
return j
}
5 changes: 5 additions & 0 deletions scheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,11 @@ func (s *Scheduler) scheduleNextRun(job *Job) {

durationToNextRun := s.durationToNextRun(job)
job.nextRun = job.lastRun.Add(durationToNextRun)

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

func (s *Scheduler) durationToNextRun(job *Job) time.Duration {
Expand Down
26 changes: 26 additions & 0 deletions scheduler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -881,3 +881,29 @@ func TestDo(t *testing.T) {
})
}
}

func TestRemoveAfterExec(t *testing.T) {
f := func(s *Scheduler) {
fmt.Print("i'm a dummy task")
}

s := NewScheduler(time.UTC)
s.StartAsync()

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

job1.LimitRunsTo(1)
job1.RemoveAfterLastExec()

time.Sleep(15 * time.Second)

var jobExists bool
for _, j := range s.jobs {
if j == job1 {
jobExists = true
}
}

assert.False(t, jobExists)
}

0 comments on commit 6ed05ca

Please sign in to comment.