github.com/ngicks/gokugen@v0.0.5/cron/schedule_state.go (about) 1 package cron 2 3 //go:generate mockgen -source schedule_state.go -destination __mock/schedule_state.go 4 5 import ( 6 "time" 7 ) 8 9 type NextScheduler interface { 10 NextSchedule(now time.Time) (time.Time, error) 11 } 12 13 // ScheduleState is a simple state storage for NextScheduler. 14 // 15 // All methods of ScheduleState are not concurrent-safe. Multiple goroutine must not call them directly. 16 type ScheduleState struct { 17 prevTime time.Time 18 nextScheduler NextScheduler 19 callCount int 20 } 21 22 // NewScheduleState creates new ScheduleState. 23 // nextScheduler is schedule-time calculator implementation. NextSchedule is called with fromWhen or, 24 // for twice or later time, previous output of the method. 25 // fromWhen is the time from when calcuation starts. Next sticks to its location. 26 func NewScheduleState(nextScheduler NextScheduler, fromWhen time.Time) *ScheduleState { 27 return &ScheduleState{ 28 nextScheduler: nextScheduler, 29 prevTime: fromWhen, 30 } 31 } 32 33 // Next returns next schedule time. 34 // If `same` is false, `next` is larger value than previously returned value. 35 // Otherwise it is same time. 36 func (s *ScheduleState) Next() (same bool, callCount int, next time.Time) { 37 next, _ = s.nextScheduler.NextSchedule(s.prevTime) 38 if next.Equal(s.prevTime) { 39 same = true 40 } 41 next = next.In(s.prevTime.Location()) 42 s.prevTime = next 43 callCount = s.callCount 44 s.callCount++ 45 return 46 }