-
Notifications
You must be signed in to change notification settings - Fork 152
/
cron.go
65 lines (56 loc) · 1.69 KB
/
cron.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package cron
import (
"time"
roboCron "github.com/robfig/cron/v3"
)
type ScheduleSpec struct {
schd roboCron.Schedule
}
// Next accepts the time and returns the next run time that should
// be used for execution
func (s *ScheduleSpec) Next(t time.Time) time.Time {
return s.schd.Next(t)
}
// ParseCronSchedule can parse standard cron notation
// it returns a new crontab schedule representing the given
// standardSpec (https://en.wikipedia.org/wiki/Cron). It requires 5 entries
// representing: minute, hour, day of month, month and day of week, in that
// order. It returns a descriptive error if the spec is not valid.
//
// It accepts
// - Standard crontab specs, e.g. "* * * * ?"
// - Descriptors, e.g. "@midnight", "@every 1h30m"
func ParseCronSchedule(interval string) (*ScheduleSpec, error) {
roboCronSchedule, err := roboCron.ParseStandard(interval)
if err != nil {
return nil, err
}
return &ScheduleSpec{
schd: roboCronSchedule,
}, nil
}
func (s *ScheduleSpec) Prev(currTime time.Time) time.Time {
startTime := s.getEarliestTimeToStartCron(currTime)
return s.getPreviousSchedule(currTime, startTime)
}
func (s *ScheduleSpec) getPreviousSchedule(currTime, startTime time.Time) time.Time {
previousSchedule := startTime
for {
nextSchedule := s.Next(previousSchedule)
if nextSchedule.After(currTime) || nextSchedule.Equal(currTime) {
return previousSchedule
}
previousSchedule = nextSchedule
}
}
func (s *ScheduleSpec) getEarliestTimeToStartCron(currTime time.Time) time.Time {
initialDelay := -time.Hour * 24 * 7 //nolint:gomnd
startTime := currTime
for {
startTime = startTime.Add(initialDelay)
if s.Next(startTime).Before(currTime) {
break
}
}
return startTime
}