Skip to content

Commit

Permalink
Adaptations and cleaning
Browse files Browse the repository at this point in the history
* Fix scheduler not working with seconds
* Add StartWithContext method
StartWithContext starts all pending jobs,
It blocks until ctx is done, or the service returns an error.
* Add len & fix for non running jobs with weeks or days units
* Remove not needed files
  • Loading branch information
Frédéric Selvi committed Feb 8, 2019
1 parent 964915f commit ba3acb0
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 42 deletions.
17 changes: 0 additions & 17 deletions .circleci/config.yml

This file was deleted.

17 changes: 0 additions & 17 deletions .golangci.yml

This file was deleted.

7 changes: 0 additions & 7 deletions Makefile

This file was deleted.

30 changes: 29 additions & 1 deletion gocron.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
package gocron

import (
"context"
"errors"
"fmt"
"reflect"
Expand Down Expand Up @@ -239,9 +240,11 @@ func (j *Job) scheduleNextRun() error {

switch j.unit {
case days:
j.shouldDo = true
j.nextRun = j.roundToMidnight(j.lastRun)
j.nextRun = j.nextRun.Add(j.atTime)
case weeks:
j.shouldDo = true
j.nextRun = j.roundToMidnight(j.lastRun)
dayDiff := int(j.startDay)
dayDiff -= int(j.nextRun.Weekday())
Expand All @@ -259,7 +262,7 @@ func (j *Job) scheduleNextRun() error {
}

// advance to next possible schedule
for j.nextRun.Before(now) || j.nextRun.Before(j.lastRun) {
for j.nextRun.Before(now) || j.nextRun.Equal(now) || j.nextRun.Before(j.lastRun) {
j.shouldDo = true
j.nextRun = j.nextRun.Add(period)
}
Expand Down Expand Up @@ -527,6 +530,26 @@ func (s *Scheduler) Start() chan bool {
return stopped
}

// StartWithContext starts all pending jobs
// It blocks until ctx is done, or the service returns an error.
func (s *Scheduler) StartWithContext(ctx context.Context) error {
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()

for {
select {
case <-ticker.C:
err := s.RunPending()
if err != nil {
s.err = err
return err
}
case <-ctx.Done():
return nil
}
}
}

// The following methods are shortcuts for not having to
// create a Schduler instance
var defaultScheduler = NewScheduler()
Expand Down Expand Up @@ -578,3 +601,8 @@ func Remove(j interface{}) {
func NextRun() (job *Job, time time.Time) {
return defaultScheduler.NextRun()
}

// Len gets the amount of jobs in the scheduler
func Len() int {
return defaultScheduler.Len()
}

0 comments on commit ba3acb0

Please sign in to comment.