-
Notifications
You must be signed in to change notification settings - Fork 387
/
Task.go
344 lines (284 loc) · 7.98 KB
/
Task.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
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package bacnetip
import (
"fmt"
"github.com/rs/zerolog/log"
"sync"
"time"
)
type _TaskRequirements interface {
processTask() error
InstallTask(when *time.Time, delta *time.Duration)
getTaskTime() *time.Time
getIsScheduled() bool
setIsScheduled(isScheduled bool)
}
type _Task struct {
taskRequirements _TaskRequirements
taskTime *time.Time
isScheduled bool
}
func _New_Task(_TaskRequirements _TaskRequirements) *_Task {
return &_Task{taskRequirements: _TaskRequirements}
}
func (t *_Task) InstallTask(when *time.Time, delta *time.Duration) {
// check for delta from now
if when == nil && delta != nil {
_when := _taskManager.getTime().Add(*delta)
when = &_when
}
// fallback to the initial value
if when == nil {
_when := t.taskTime
when = _when
}
if when == nil {
panic("schedule missing, use zero for 'now'")
}
t.taskTime = when
// pass along to the task manager
_taskManager.installTask(t.taskRequirements)
}
func (t *_Task) SuspendTask() {
_taskManager.suspendTask(t.taskRequirements)
}
func (t *_Task) Resume() {
_taskManager.resumeTask(t.taskRequirements)
}
func (t *_Task) getTaskTime() *time.Time {
return t.taskTime
}
func (t *_Task) getIsScheduled() bool {
return t.isScheduled
}
func (t *_Task) setIsScheduled(isScheduled bool) {
t.isScheduled = isScheduled
}
func (t *_Task) String() string {
return fmt.Sprintf("Task(taskTime: %v, isScheduled: %v)", t.taskTime, t.isScheduled)
}
type OneShotTaskRequirements interface {
processTask() error
}
type OneShotTask struct {
*_Task
OneShotTaskRequirements
}
func NewOneShotTask(oneShotTaskRequirements OneShotTaskRequirements, when *time.Time) *OneShotTask {
o := &OneShotTask{
OneShotTaskRequirements: oneShotTaskRequirements,
}
o._Task = _New_Task(o)
if when != nil {
o.taskTime = when
}
return o
}
type OneShotDeleteTask struct {
*_Task
OneShotTaskRequirements
}
func NewOneShotDeleteTask(oneShotTaskRequirements OneShotTaskRequirements, when *time.Time) *OneShotDeleteTask {
o := &OneShotDeleteTask{OneShotTaskRequirements: oneShotTaskRequirements}
o._Task = _New_Task(o)
if when != nil {
o.taskTime = when
}
return o
}
func (r *OneShotDeleteTask) IsOneShotDeleteTask() bool {
return true
}
type OneShotFunctionTask struct {
*OneShotDeleteTask
fn func() error
}
func (m *OneShotFunctionTask) processTask() error {
return m.fn()
}
func OneShotFunction(fn func() error) *OneShotFunctionTask {
task := &OneShotFunctionTask{fn: fn}
task.OneShotDeleteTask = NewOneShotDeleteTask(task, nil)
var delta time.Duration = 0
task.InstallTask(nil, &delta)
return task
}
func FunctionTask(fn func() error) *OneShotFunctionTask {
task := &OneShotFunctionTask{fn: fn}
task.OneShotDeleteTask = NewOneShotDeleteTask(task, nil)
log.Debug().Stringer("task", task).Msg("task")
return task
}
type RecurringTaskRequirements interface {
processTask() error
}
type RecurringTask struct {
*_Task
RecurringTaskRequirements
taskInterval *time.Duration
taskIntervalOffset *time.Duration
}
func NewRecurringTask(recurringTaskRequirements RecurringTaskRequirements, interval *time.Duration, offset *time.Duration) *RecurringTask {
r := &RecurringTask{RecurringTaskRequirements: recurringTaskRequirements}
r._Task = _New_Task(r)
// set the interval if it hasn't already been set
if interval != nil {
r.taskInterval = interval
}
if offset != nil {
r.taskIntervalOffset = offset
}
if r.taskInterval == nil {
panic("interval unset, use ctor or install_task parameter")
}
if *r.taskInterval <= 0.0 {
panic("interval must be greater than zero")
}
// get ready for the next interval plus a jitter
now := _taskManager.getTime().Add(10 + time.Nanosecond)
if r.taskIntervalOffset != nil {
_offset := *r.taskIntervalOffset
offset = &_offset
} else {
_offset := time.Duration(0)
offset = &_offset
}
log.Debug().
Interface("now", now).
Interface("interval", interval).
Interface("offset", offset).
Msg("Now, interval, offset:")
// compute the time
_taskTime := now.Add(-*offset).Add(*interval) // TODO: check why upstream is doing the modulo operation (missing code here)
r.taskTime = &_taskTime
// install it
_taskManager.installTask(r)
return r
}
func (r *RecurringTask) IsRecurringTask() bool {
return true
}
type _RecurringFunctionTask struct {
*RecurringTask
fn func() error
}
func _New_RecurringFunctionTask(interval *time.Duration, fn func() error) *_RecurringFunctionTask {
r := &_RecurringFunctionTask{fn: fn}
r.RecurringTask = NewRecurringTask(r, interval, nil)
return r
}
func (r _RecurringFunctionTask) processTask() error {
return r.fn()
}
func RecurringFunctionTask(interval *time.Duration, fn func() error) *RecurringTask {
return _New_RecurringFunctionTask(interval, fn).RecurringTask
}
var _taskManager = TaskManager{}
type TaskManager struct {
sync.Mutex
tasks []_TaskRequirements
}
func (m *TaskManager) getTime() time.Time {
return time.Now()
}
func (m *TaskManager) installTask(task _TaskRequirements) {
m.Lock()
defer m.Unlock()
log.Debug().Interface("task", task).Msg("installTask")
// if the taskTime is None is hasn't been computed correctly
if task.getTaskTime() == nil {
panic("task time is None")
}
// if this is already installed, suspend it
if task.getIsScheduled() {
m.suspendTask(task)
}
// save this in the task list
// TODO: we might need to insert it at the right place
m.tasks = append(m.tasks, task)
task.setIsScheduled(true)
}
func (m *TaskManager) suspendTask(task _TaskRequirements) {
log.Debug().Interface("task", task).Msg("suspendTask ")
m.Lock()
defer m.Unlock()
iToDelete := -1
for i, _task := range m.tasks {
if _task == task {
log.Debug().Msg("task found")
iToDelete = i
task.setIsScheduled(false)
break
}
}
if iToDelete > 0 {
m.tasks = append(m.tasks[:iToDelete], m.tasks[iToDelete+1:]...)
} else {
log.Debug().Msg("task not found")
}
}
func (m *TaskManager) resumeTask(task _TaskRequirements) {
log.Debug().Interface("task", task).Msg("resumeTask")
m.Lock()
defer m.Unlock()
// just re-install it
m.installTask(task)
}
func (m *TaskManager) getNextTask() (_TaskRequirements, time.Duration) {
//log.Trace().Msg("getNextTask")
m.Lock()
defer m.Unlock()
now := time.Now()
var task _TaskRequirements
var delta time.Duration
if len(m.tasks) > 0 {
nextTask := m.tasks[0]
when := nextTask.getTaskTime()
if when.Before(now) {
// pull it off the list and mark that it's no longer scheduled
m.tasks = m.tasks[1:] // TODO: guard against empty list
task = nextTask
task.setIsScheduled(false)
if len(m.tasks) > 0 {
nextTask = m.tasks[0]
when = nextTask.getTaskTime()
// peek at the next task, return how long to wait
delta = when.Sub(now) // TODO: avoid negative
}
} else {
delta = when.Sub(now)
}
}
// return the task to run and how long to wait for the next one
return task, delta
}
func (m *TaskManager) processTask(task _TaskRequirements) {
log.Debug().Interface("task", task).Msg("processTask")
// process the task
if err := task.processTask(); err != nil {
log.Error().Err(err).Msg("Error processing Task")
}
switch task.(type) {
case interface{ IsRecurringTask() bool }:
task.InstallTask(nil, nil)
case interface{ IsOneShotDeleteTask() bool }:
// TODO: Delete? How?
}
}