-
Notifications
You must be signed in to change notification settings - Fork 0
/
cron.go
114 lines (98 loc) · 2.34 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
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package service
import (
"errors"
"math/rand"
"strings"
"time"
"github.com/robfig/cron/v3"
)
const (
// randomly is used to generate random time.
// example:
// '@randomly' means 00:00:00~23:59:59
// '@randomly 8:00:00' means 8:00:00~23:59:59
// '@randomly 8:00:00 23:00:00' means 8:00:00~23:00:00
randomly = "@randomly"
randomLayout = "15:04:05"
randomStart = "00:00:00"
randomEnd = "23:59:59"
)
var (
ErrInvalidRandomly = errors.New("invalid randomly expression")
randomStartTime, _ = time.ParseInLocation(randomLayout, randomStart, time.UTC)
)
func parseRanges(ts []string) ([]time.Time, error) {
result := make([]time.Time, 0, len(ts))
for _, v := range ts {
if v == "" {
result = append(result, randomStartTime)
continue
}
t, err := time.ParseInLocation(randomLayout, v, time.UTC)
if err != nil {
return nil, err
}
result = append(result, t)
}
return result, nil
}
func newRandomSchedule(spec string) (*randomSchedule, error) {
spec = strings.TrimSpace(strings.TrimPrefix(spec, randomly))
ranges := strings.Split(spec, " ")
if len(ranges) == 1 {
ranges = append(ranges, randomEnd)
} else if len(ranges) > 2 {
return nil, ErrInvalidRandomly
}
result, err := parseRanges(ranges)
if err != nil {
return nil, err
}
start, end := result[0], result[1]
if start.After(end) {
return nil, ErrInvalidRandomly
}
return &randomSchedule{
start: start,
end: end,
}, nil
}
type randomSchedule struct {
start time.Time
end time.Time
}
func (rs *randomSchedule) offset() time.Duration {
d1 := rs.end.Sub(rs.start)
if d1.Nanoseconds() == 0 {
return 0
}
d2 := time.Duration(rand.Int63n(d1.Nanoseconds()))
d3 := rs.start.Sub(randomStartTime)
return d2 + d3
}
// Next 返回明天的某个时间
func (rs *randomSchedule) Next(t time.Time) time.Time {
var (
year = t.Year()
month = t.Month()
day = t.Day()
)
return time.Date(year, month, day, 0, 0, 0, 0, t.Location()).
AddDate(0, 0, 1).
Add(rs.offset())
}
func (s *Service) parse(spec string) (cron.Schedule, error) {
switch {
case strings.HasPrefix(spec, randomly):
return newRandomSchedule(spec)
}
return s.parser.Parse(spec)
}
func (s *Service) addJob(spec string, cmd cron.Job) error {
schedule, err := s.parse(spec)
if err != nil {
return err
}
s.cron.Schedule(schedule, cmd)
return nil
}