-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathschedule_processor.go
115 lines (101 loc) · 2.5 KB
/
schedule_processor.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
package command
import (
"sync"
"time"
"github.com/google/uuid"
)
type scheduleProcessor struct {
sync.Mutex
bus *Bus
scheduledCommands map[uuid.UUID]*scheduledCommand
triggerSignal chan bool
shuttingDown *flag
sleepTimer *time.Timer
sleepUntil time.Time
}
func newScheduleProcessor(bus *Bus) *scheduleProcessor {
pro := &scheduleProcessor{
bus: bus,
scheduledCommands: make(map[uuid.UUID]*scheduledCommand),
triggerSignal: make(chan bool, 1),
shuttingDown: newFlag(),
}
go pro.process()
return pro
}
func (pro *scheduleProcessor) add(schCmd *scheduledCommand) uuid.UUID {
pro.Lock()
key := uuid.New()
pro.scheduledCommands[key] = schCmd
pro.Unlock()
pro.trigger()
return key
}
func (pro *scheduleProcessor) remove(keys ...uuid.UUID) {
pro.Lock()
for _, key := range keys {
delete(pro.scheduledCommands, key)
}
pro.Unlock()
pro.trigger()
}
func (pro *scheduleProcessor) shutdown() {
if pro.shuttingDown.enable() {
pro.trigger()
}
}
func (pro *scheduleProcessor) process() {
for !pro.shuttingDown.enabled() {
pro.Lock()
now := time.Now()
pro.sleepUntil = time.Time{}
for key, schCmd := range pro.scheduledCommands {
following := schCmd.sch.Following()
if following.IsZero() {
_ = schCmd.sch.Next()
following = schCmd.sch.Following()
}
if now.After(following) || now.Equal(following) {
async := newAsync(schCmd.hdl, schCmd.cmd)
pro.bus.asyncCommandsQueue <- async
if err := schCmd.sch.Next(); err != nil {
delete(pro.scheduledCommands, key)
continue
}
following = schCmd.sch.Following()
}
pro.updateSleepUntil(following)
}
pro.updateSleepTimer(pro.determineSleepDuration())
pro.Unlock()
// allow the processor to be triggered either with timer or directly
select {
case <-pro.sleepTimer.C:
case <-pro.triggerSignal:
}
}
}
func (pro *scheduleProcessor) trigger() {
select {
case pro.triggerSignal <- true:
default:
}
}
func (pro *scheduleProcessor) updateSleepUntil(nextTrigger time.Time) {
if pro.sleepUntil.IsZero() || nextTrigger.Before(pro.sleepUntil) {
pro.sleepUntil = nextTrigger
}
}
func (pro *scheduleProcessor) determineSleepDuration() time.Duration {
if pro.sleepUntil.IsZero() || len(pro.scheduledCommands) <= 0 {
return time.Hour
}
return time.Until(pro.sleepUntil)
}
func (pro *scheduleProcessor) updateSleepTimer(d time.Duration) {
if pro.sleepTimer == nil {
pro.sleepTimer = time.NewTimer(d)
return
}
pro.sleepTimer.Reset(d)
}