-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathschedule.go
More file actions
220 lines (189 loc) · 5.57 KB
/
Copy pathschedule.go
File metadata and controls
220 lines (189 loc) · 5.57 KB
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package gomeassistant
import (
"context"
"fmt"
"log/slog"
"time"
"github.com/golang-module/carbon"
"saml.dev/gome-assistant/internal"
)
type ScheduleCallback func(*Service, State)
// DailySchedule is a `scheduledAction` that runs once per day.
type DailySchedule struct {
// 0-23
hour int
// 0-59
minute int
callback ScheduleCallback
nextRunTime time.Time
isSunrise bool
isSunset bool
sunOffset DurationString
exceptionDates []time.Time
allowlistDates []time.Time
enabledEntities []internal.EnabledDisabledInfo
disabledEntities []internal.EnabledDisabledInfo
}
func (s DailySchedule) Hash() string {
return fmt.Sprint(s.hour, s.minute, s.callback)
}
type scheduleBuilder struct {
schedule DailySchedule
}
type scheduleBuilderCall struct {
schedule DailySchedule
}
type scheduleBuilderEnd struct {
schedule DailySchedule
}
func NewDailySchedule() scheduleBuilder {
return scheduleBuilder{
DailySchedule{
hour: 0,
minute: 0,
sunOffset: "0s",
},
}
}
func (s DailySchedule) String() string {
return fmt.Sprintf("Schedule{ call %q daily at %s }",
internal.GetFunctionName(s.callback),
stringHourMinute(s.hour, s.minute),
)
}
func stringHourMinute(hour, minute int) string {
return fmt.Sprintf("%02d:%02d", hour, minute)
}
func (sb scheduleBuilder) Call(callback ScheduleCallback) scheduleBuilderCall {
sb.schedule.callback = callback
return scheduleBuilderCall(sb)
}
// At takes a string in 24hr format time like "15:30".
func (sb scheduleBuilderCall) At(s string) scheduleBuilderEnd {
t := internal.ParseTime(s)
sb.schedule.hour = t.Hour()
sb.schedule.minute = t.Minute()
return scheduleBuilderEnd(sb)
}
// Sunrise takes an optional duration string that is passed to time.ParseDuration.
// Examples include "-1.5h", "30m", etc. See https://pkg.go.dev/time#ParseDuration
// for full list.
func (sb scheduleBuilderCall) Sunrise(offset ...DurationString) scheduleBuilderEnd {
sb.schedule.isSunrise = true
if len(offset) > 0 {
sb.schedule.sunOffset = offset[0]
}
return scheduleBuilderEnd(sb)
}
// Sunset takes an optional duration string that is passed to time.ParseDuration.
// Examples include "-1.5h", "30m", etc. See https://pkg.go.dev/time#ParseDuration
// for full list.
func (sb scheduleBuilderCall) Sunset(offset ...DurationString) scheduleBuilderEnd {
sb.schedule.isSunset = true
if len(offset) > 0 {
sb.schedule.sunOffset = offset[0]
}
return scheduleBuilderEnd(sb)
}
func (sb scheduleBuilderEnd) ExceptionDates(t time.Time, tl ...time.Time) scheduleBuilderEnd {
sb.schedule.exceptionDates = append(tl, t)
return sb
}
func (sb scheduleBuilderEnd) OnlyOnDates(t time.Time, tl ...time.Time) scheduleBuilderEnd {
sb.schedule.allowlistDates = append(tl, t)
return sb
}
/*
Enable this schedule only when the current state of {entityID} matches {state}.
If there is a network error while retrieving state, the schedule runs if {runOnNetworkError} is true.
*/
func (sb scheduleBuilderEnd) EnabledWhen(entityID, state string, runOnNetworkError bool) scheduleBuilderEnd {
if entityID == "" {
panic(fmt.Sprintf("entityID is empty in EnabledWhen entityID='%s' state='%s'", entityID, state))
}
i := internal.EnabledDisabledInfo{
Entity: entityID,
State: state,
RunOnError: runOnNetworkError,
}
sb.schedule.enabledEntities = append(sb.schedule.enabledEntities, i)
return sb
}
/*
Disable this schedule when the current state of {entityID} matches {state}.
If there is a network error while retrieving state, the schedule runs if {runOnNetworkError} is true.
*/
func (sb scheduleBuilderEnd) DisabledWhen(entityID, state string, runOnNetworkError bool) scheduleBuilderEnd {
if entityID == "" {
panic(fmt.Sprintf("entityID is empty in EnabledWhen entityID='%s' state='%s'", entityID, state))
}
i := internal.EnabledDisabledInfo{
Entity: entityID,
State: state,
RunOnError: runOnNetworkError,
}
sb.schedule.disabledEntities = append(sb.schedule.disabledEntities, i)
return sb
}
func (sb scheduleBuilderEnd) Build() DailySchedule {
return sb.schedule
}
// run invokes `s.maybeRunCallback()` based on its configured
// schedule. Terminate when `ctx` is canceled.
func (s *DailySchedule) run(ctx context.Context, app *App) {
// Create a new, but stopped, timer for sleeping on:
timer := time.NewTimer(1 * time.Hour)
if !timer.Stop() {
<-timer.C
}
defer stopAndDrainTimer(timer)
for ctx.Err() == nil {
if s.nextRunTime.After(time.Now()) {
slog.Info("Next schedule", "start_time", s.nextRunTime)
timer.Reset(time.Until(s.nextRunTime))
select {
case <-timer.C:
case <-ctx.Done():
return
}
}
s.maybeRunCallback(app)
s.updateNextRunTime(app)
}
}
func (s DailySchedule) maybeRunCallback(app *App) {
if c := checkExceptionDates(s.exceptionDates); c.fail {
return
}
if c := checkAllowlistDates(s.allowlistDates); c.fail {
return
}
if c := checkEnabledEntity(app.state, s.enabledEntities); c.fail {
return
}
if c := checkDisabledEntity(app.state, s.disabledEntities); c.fail {
return
}
if app.ctx.Err() != nil {
return
}
app.goTracked(func() {
s.callback(app.service, app.state)
})
}
// updateNextRunTime updates `s.nextRunTime` to the next time that `s`
// should run.
func (s *DailySchedule) updateNextRunTime(app *App) {
if s.isSunrise || s.isSunset {
var nextSunTime carbon.Carbon
// "0s" is default value
if s.sunOffset != "0s" {
nextSunTime = getNextSunRiseOrSet(app, s.isSunrise, s.sunOffset)
} else {
nextSunTime = getNextSunRiseOrSet(app, s.isSunrise)
}
s.nextRunTime = nextSunTime.Carbon2Time()
} else {
s.nextRunTime = carbon.Time2Carbon(s.nextRunTime).AddDay().Carbon2Time()
}
}