-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathschedule.go
105 lines (87 loc) · 1.92 KB
/
schedule.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
package flamingo
import "time"
// ScheduleTime gives the next time to run a job.
type ScheduleTime interface {
// Next time right after the given time a job should be run.
Next(time.Time) time.Time
}
type intervalSchedule struct {
every time.Duration
}
// NewIntervalSchedule creates a ScheduleTime that runs in intervals
// of the given duration.
func NewIntervalSchedule(every time.Duration) ScheduleTime {
return &intervalSchedule{
every,
}
}
func (s *intervalSchedule) Next(now time.Time) time.Time {
return now.Add(s.every)
}
type timeSchedule struct {
hour, minutes, seconds int
}
// NewTimeSchedule creates a ScheduleTime that runs once a day at a given
// hour, minutes and seconds.
func NewTimeSchedule(hour, minutes, seconds int) ScheduleTime {
return &timeSchedule{
hour, minutes, seconds,
}
}
func (s *timeSchedule) Next(now time.Time) time.Time {
d := time.Date(
now.Year(),
now.Month(),
now.Day(),
s.hour,
s.minutes,
s.seconds,
0,
now.Location(),
)
if d.Before(now) {
d = d.Add(24 * time.Hour)
}
return d
}
type dayTimeSchedule struct {
days map[time.Weekday]struct{}
hour, minutes, seconds int
}
// NewDayTimeSchedule creates a ScheduleTime that runs once a day at a given
// hour, minutes and seconds only on the given set of days.
func NewDayTimeSchedule(days []time.Weekday, hour, minutes, seconds int) ScheduleTime {
var daySet = make(map[time.Weekday]struct{})
for _, d := range days {
daySet[d] = struct{}{}
}
return &dayTimeSchedule{
daySet,
hour, minutes, seconds,
}
}
var zero time.Time
func (s *dayTimeSchedule) Next(now time.Time) time.Time {
if len(s.days) == 0 {
return zero
}
var t = now
for {
if _, ok := s.days[t.Weekday()]; ok {
d := time.Date(
t.Year(),
t.Month(),
t.Day(),
s.hour,
s.minutes,
s.seconds,
0,
t.Location(),
)
if d.After(now) {
return d
}
}
t = t.Add(24 * time.Hour)
}
}