Skip to content

Commit 9993f76

Browse files
husam-eJohnRoesler
andauthored
fix(scheduler): ensure negative intervals given to Every return an immediate error #600 (#603)
* fix(scheduler): ensure negative intervals given to `Every` return an immediate error #600 * Update Every func doc * fix error check in tests Co-authored-by: John Roesler <johnrroesler@gmail.com> * Apply suggestions from code review * Apply suggestions from code review * Update scheduler_test.go --------- Co-authored-by: John Roesler <johnrroesler@gmail.com>
1 parent 912b4a7 commit 9993f76

2 files changed

Lines changed: 12 additions & 3 deletions

File tree

scheduler.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -537,6 +537,7 @@ func (s *Scheduler) EveryRandom(lower, upper int) *Scheduler {
537537
// Every schedules a new periodic Job with an interval.
538538
// Interval can be an int, time.Duration or a string that
539539
// parses with time.ParseDuration().
540+
// Negative intervals will return an error.
540541
// Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
541542
//
542543
// The job is run immediately, unless:
@@ -553,6 +554,9 @@ func (s *Scheduler) Every(interval interface{}) *Scheduler {
553554
job.error = wrapOrError(job.error, ErrInvalidInterval)
554555
}
555556
case time.Duration:
557+
if interval <= 0 {
558+
job.error = wrapOrError(job.error, ErrInvalidInterval)
559+
}
556560
job.setInterval(0)
557561
job.setDuration(interval)
558562
job.setUnit(duration)
@@ -561,6 +565,9 @@ func (s *Scheduler) Every(interval interface{}) *Scheduler {
561565
if err != nil {
562566
job.error = wrapOrError(job.error, err)
563567
}
568+
if d <= 0 {
569+
job.error = wrapOrError(job.error, ErrInvalidInterval)
570+
}
564571
job.setDuration(d)
565572
job.setUnit(duration)
566573
default:

scheduler_test.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -82,8 +82,10 @@ func TestScheduler_Every_InvalidInterval(t *testing.T) {
8282
interval interface{}
8383
expectedError string
8484
}{
85-
{"zero", 0, ErrInvalidInterval.Error()},
86-
{"negative", -1, ErrInvalidInterval.Error()},
85+
{"zero int", 0, ErrInvalidInterval.Error()},
86+
{"negative int", -1, ErrInvalidInterval.Error()},
87+
{"negative time.Duration", -1 * time.Millisecond, ErrInvalidInterval.Error()},
88+
{"negative string duration", "-1ms", ErrInvalidInterval.Error()},
8789
{"invalid string duration", "bad", "time: invalid duration \"bad\""},
8890
}
8991

@@ -93,7 +95,7 @@ func TestScheduler_Every_InvalidInterval(t *testing.T) {
9395
t.Run(tc.description, func(t *testing.T) {
9496
_, err := s.Every(tc.interval).Do(func() {})
9597
require.Error(t, err)
96-
assert.EqualError(t, err, tc.expectedError)
98+
assert.ErrorContains(t, err, tc.expectedError)
9799
})
98100
}
99101
}

0 commit comments

Comments
 (0)