Skip to content

Commit

Permalink
Implement an iterator
Browse files Browse the repository at this point in the history
  • Loading branch information
Gilthoniel committed Dec 3, 2023
1 parent 34e6556 commit 0fc5008
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
27 changes: 27 additions & 0 deletions cron.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,30 @@ func (s Schedule) nextAfter(after time.Time) (time.Time, bool) {
}
return after, true
}

// Upcoming returns an iterator that will iterate oover the activation times of
// the Cron expression of the schedule.
func (s Schedule) Upcoming(after time.Time) *Iterator {
i := &Iterator{schedule: s, next: after}
i.Next() // initialize the first value of the iterator.
return i
}

type Iterator struct {
schedule Schedule
next time.Time
}

// HasNext returns true if an activation time is available. When it returns
// false, any call to `Next` will return a zero time.
func (i *Iterator) HasNext() bool {
return !i.next.IsZero()
}

// Next returns the next activation time of the schedule, or a zero time if none
// is available.
func (i *Iterator) Next() (next time.Time) {
next = i.next
i.next = i.schedule.Next(next)
return
}
17 changes: 17 additions & 0 deletions examples_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,20 @@ func ExampleSchedule_Next_everyLastFridayOfTheMonthAtMidnight() {
// 2023-06-30 00:00:00 +0000 UTC
// 2023-07-28 00:00:00 +0000 UTC
}

func ExampleSchedule_Upcoming_everyLastSundayOfAprilAtThreePM() {
schedule := gocron.Must("0 0 15 ? 4 0L")

iter := schedule.Upcoming(time.Date(2023, time.June, 4, 0, 0, 0, 0, time.UTC))
for i := 0; i < 5 && iter.HasNext(); i++ {
next := iter.Next()
fmt.Println(next)
}

// Output:
// 2024-04-28 15:00:00 +0000 UTC
// 2025-04-27 15:00:00 +0000 UTC
// 2026-04-26 15:00:00 +0000 UTC
// 2027-04-25 15:00:00 +0000 UTC
// 2028-04-30 15:00:00 +0000 UTC
}

0 comments on commit 0fc5008

Please sign in to comment.