-
-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathchecker.go
99 lines (83 loc) · 2.02 KB
/
checker.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package gronx
import (
"strconv"
"strings"
"time"
)
// Checker is interface for cron segment due check.
type Checker interface {
GetRef() time.Time
SetRef(ref time.Time)
CheckDue(segment string, pos int) (bool, error)
}
// SegmentChecker is factory implementation of Checker.
type SegmentChecker struct {
ref time.Time
}
// GetRef returns the current reference time
func (c *SegmentChecker) GetRef() time.Time {
return c.ref
}
// SetRef sets the reference time for which to check if a cron expression is due.
func (c *SegmentChecker) SetRef(ref time.Time) {
c.ref = ref
}
// CheckDue checks if the cron segment at given position is due.
// It returns bool or error if any.
func (c *SegmentChecker) CheckDue(segment string, pos int) (bool, error) {
ref := c.GetRef()
val, loc := valueByPos(ref, pos), ref.Location()
last := time.Date(ref.Year(), ref.Month(), 1, 0, 0, 0, 0, loc).AddDate(0, 1, 0).Add(-time.Nanosecond).Day()
for _, offset := range strings.Split(segment, ",") {
mod := pos == 2 || pos == 4
due, err := c.isOffsetDue(offset, val)
if due || (!mod && err != nil) {
return due, err
}
if mod && !strings.ContainsAny(offset, "LW#") {
continue
}
if pos == 2 {
due, err = isValidMonthDay(offset, last, ref)
} else if pos == 4 {
due, err = isValidWeekDay(offset, last, ref)
}
if due || err != nil {
return due, err
}
}
return false, nil
}
func (c *SegmentChecker) isOffsetDue(offset string, val int) (bool, error) {
if strings.Contains(offset, "/") {
return inStep(val, offset)
}
if strings.Contains(offset, "-") {
return inRange(val, offset)
}
if val == 0 || offset == "0" {
return offset == "0" && val == 0, nil
}
nval, err := strconv.Atoi(offset)
if err != nil {
return false, err
}
return nval == val, nil
}
func valueByPos(ref time.Time, pos int) int {
switch pos {
case 0:
return ref.Minute()
case 1:
return ref.Hour()
case 2:
return ref.Day()
case 3:
return int(ref.Month())
case 4:
return int(ref.Weekday())
case 5:
return ref.Year()
}
return 0
}