-
Notifications
You must be signed in to change notification settings - Fork 16
/
scheduler.go
187 lines (152 loc) · 4.1 KB
/
scheduler.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
package sarah
import (
"context"
"fmt"
"github.com/oklahomer/go-kasumi/logger"
"github.com/robfig/cron/v3"
"strings"
"time"
)
type scheduler interface {
remove(BotType, string)
update(BotType, ScheduledTask, func()) error
}
type taskScheduler struct {
cron *cron.Cron
removingTask chan *removingTask
updatingTask chan *updatingTask
}
func (s *taskScheduler) remove(botType BotType, taskID string) {
remove := &removingTask{
botType: botType,
taskID: taskID,
}
s.removingTask <- remove
}
func (s *taskScheduler) update(botType BotType, task ScheduledTask, fn func()) error {
add := &updatingTask{
botType: botType,
task: task,
fn: fn,
err: make(chan error, 1),
}
s.updatingTask <- add
return <-add.err
}
type removingTask struct {
botType BotType
taskID string
}
type updatingTask struct {
botType BotType
task ScheduledTask
fn func()
err chan error
}
func runScheduler(ctx context.Context, location *time.Location) scheduler {
c := cron.New(cron.WithLocation(location), cron.WithLogger(&cronLogAdapter{l: logger.GetLogger()}))
c.Start()
s := &taskScheduler{
cron: c,
removingTask: make(chan *removingTask, 1),
updatingTask: make(chan *updatingTask, 1),
}
go s.receiveEvent(ctx)
return s
}
func (s *taskScheduler) receiveEvent(ctx context.Context) {
schedule := make(map[BotType]map[string]cron.EntryID)
removeFunc := func(botType BotType, taskID string) {
botSchedule, ok := schedule[botType]
if !ok {
// Task is not registered for the given bot
return
}
storedID, ok := botSchedule[taskID]
if !ok {
// Given task is not registered
return
}
delete(botSchedule, taskID)
s.cron.Remove(storedID)
}
for {
select {
case <-ctx.Done():
logger.Info("Stop cron jobs due to context cancellation.")
s.cron.Stop()
return
case remove := <-s.removingTask:
removeFunc(remove.botType, remove.taskID)
case add := <-s.updatingTask:
if add.task.Schedule() == "" {
add.err <- fmt.Errorf("empty schedule is given for %s", add.task.Identifier())
continue
}
removeFunc(add.botType, add.task.Identifier())
id, err := s.cron.AddFunc(add.task.Schedule(), add.fn)
if err != nil {
add.err <- err
break
}
if _, ok := schedule[add.botType]; !ok {
schedule[add.botType] = make(map[string]cron.EntryID)
}
schedule[add.botType][add.task.Identifier()] = id
add.err <- nil
}
}
}
type cronLogAdapter struct {
l logger.Logger
}
var _ cron.Logger = (*cronLogAdapter)(nil)
func (c *cronLogAdapter) Info(msg string, keysAndValues ...interface{}) {
converted := c.convertKeyValues(keysAndValues)
args := append([]interface{}{msg}, converted...)
format := c.formatString(len(args))
c.l.Infof(format, args...)
}
func (c *cronLogAdapter) Error(err error, msg string, keysAndValues ...interface{}) {
converted := c.convertKeyValues(keysAndValues)
args := append([]interface{}{msg, "error", err}, converted...)
format := c.formatString(len(args))
c.l.Errorf(format, args...)
}
func (c *cronLogAdapter) convertKeyValues(keysAndValues []interface{}) []interface{} {
formatted := make([]interface{}, len(keysAndValues))
for i, arg := range keysAndValues {
switch typed := arg.(type) {
case time.Time:
str := typed.Format(time.RFC3339)
formatted[i] = str
case fmt.Stringer:
str := typed.String()
formatted[i] = str
default:
formatted[i] = typed
}
}
return formatted
}
func (c *cronLogAdapter) formatString(numKeysAndValues int) string {
var sb strings.Builder
// The first argument is always a stringified log message.
sb.WriteString("%s")
// Set a delimiter when there more arguments to follow.
// Note that the first element is already taken care of.
if numKeysAndValues > 1 {
sb.WriteString(", ")
}
// Arbitrary arguments are to be formatted with %v.
// robfig/cron's code suggests that the key is always string,
// but the type is actually interface{}.
// That library's logger implementation also format with %v, after all.
for i := 0; i < numKeysAndValues/2; i++ {
if i > 0 {
sb.WriteString(", ")
}
sb.WriteString("%v=%v")
}
return sb.String()
}