-
Notifications
You must be signed in to change notification settings - Fork 78
/
timer.go
executable file
·304 lines (244 loc) · 7.25 KB
/
timer.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
package timer
import (
"context"
"math"
"strconv"
"strings"
"time"
"github.com/TIBCOSoftware/flogo-lib/core/trigger"
"github.com/TIBCOSoftware/flogo-lib/logger"
"github.com/carlescere/scheduler"
)
var log = logger.GetLogger("trigger-flogo-timer")
type TimerTrigger struct {
metadata *trigger.Metadata
config *trigger.Config
timers []*scheduler.Job
handlers []*trigger.Handler
}
//NewFactory create a new Trigger factory
func NewFactory(md *trigger.Metadata) trigger.Factory {
return &TimerFactory{metadata: md}
}
// TimerFactory Timer Trigger factory
type TimerFactory struct {
metadata *trigger.Metadata
}
//New Creates a new trigger instance for a given id
func (t *TimerFactory) New(config *trigger.Config) trigger.Trigger {
return &TimerTrigger{metadata: t.metadata, config: config}
}
// Metadata implements trigger.Trigger.Metadata
func (t *TimerTrigger) Metadata() *trigger.Metadata {
return t.metadata
}
// Init implements trigger.Init
func (t *TimerTrigger) Initialize(ctx trigger.InitContext) error {
t.handlers = ctx.GetHandlers()
return nil
}
// Start implements ext.Trigger.Start
func (t *TimerTrigger) Start() error {
log.Debug("Start")
handlers := t.handlers
log.Debug("Processing handlers")
for _, handler := range handlers {
repeating := handler.GetStringSetting("repeating")
log.Debug("Repeating: ", repeating)
if repeating == "false" {
t.scheduleOnce(handler)
} else if repeating == "true" {
t.scheduleRepeating(handler)
} else {
log.Error("No match for repeating: ", repeating)
}
log.Debug("Settings repeating: ", handler.GetStringSetting("repeating"))
//log.Debugf("Processing Handler: %s", handler.ActionId)
}
return nil
}
// Stop implements ext.Trigger.Stop
func (t *TimerTrigger) Stop() error {
log.Debug("Stopping endpoints")
for _, timer := range t.timers {
if timer.IsRunning() {
//log.Debug("Stopping timer for : ", k)
timer.Quit <- true
}
}
t.timers = nil
return nil
}
func (t *TimerTrigger) scheduleOnce(endpoint *trigger.Handler) {
log.Info("Scheduling a run one time job")
seconds := getInitialStartInSeconds(endpoint)
log.Debug("Seconds until trigger fires: ", seconds)
var timerJob *scheduler.Job
if seconds != 0 {
timerJob = scheduler.Every(int(seconds))
} else {
log.Debug("Start Date not specified, executing action immediately")
}
fn := func() {
log.Debug("Executing \"Once\" timer trigger")
_, err := endpoint.Handle(context.Background(), nil)
if err != nil {
log.Error("Error running handler: ", err.Error())
}
if timerJob != nil {
timerJob.Quit <- true
}
}
if seconds == 0 {
fn()
} else {
timerJob, err := timerJob.Seconds().NotImmediately().Run(fn)
if err != nil {
log.Error("Error performing scheduleOnce: ", err.Error())
}
t.timers = append(t.timers, timerJob)
}
}
func (t *TimerTrigger) scheduleRepeating(endpoint *trigger.Handler) {
log.Info("Scheduling a repeating job")
seconds := getInitialStartInSeconds(endpoint)
fn := func() {
log.Debug("-- Starting \"Repeating\" (repeat) timer action")
go func() {
_, err := endpoint.Handle(context.Background(), nil)
if err != nil {
log.Error("Error running handler: ", err.Error())
}
}()
}
if seconds > 0 {
//Start from specific time
timerJob := scheduler.Every(seconds).Seconds()
fn2 := func() {
log.Debug("-- Starting \"Repeating\" (repeat) timer action")
go func() {
if timerJob != nil {
timerJob.Quit <- true
}
if endpoint.GetStringSetting("notImmediate") == "false" {
timerJob := t.scheduleJobEverySecond(endpoint, false, fn)
t.timers = append(t.timers, timerJob)
} else {
timerJob := t.scheduleJobEverySecond(endpoint, true, fn)
t.timers = append(t.timers, timerJob)
}
}()
}
log.Debug("Seconds till trigger fires: ", seconds)
timerJob, err := timerJob.NotImmediately().Run(fn2)
if err != nil {
log.Error("Error scheduling delayed start repeating timer: ", err.Error())
}
t.timers = append(t.timers, timerJob)
} else {
if endpoint.GetStringSetting("notImmediate") == "false" {
t.scheduleJobEverySecond(endpoint, false, fn)
} else {
log.Debug("Seconds till trigger fires: ", seconds)
t.scheduleJobEverySecond(endpoint, true, fn)
}
}
}
func getInitialStartInSeconds(endpoint *trigger.Handler) int {
layout := time.RFC3339
startDate := endpoint.GetStringSetting("startDate")
if startDate == "" {
return 0
}
idx := strings.LastIndex(startDate, "Z")
timeZone := startDate[idx+1:]
log.Debug("Time Zone: ", timeZone)
startDate = strings.TrimSuffix(startDate, timeZone)
log.Debug("startDate: ", startDate)
// is timezone negative
var isNegative bool
isNegative = strings.HasPrefix(timeZone, "-")
// remove sign
timeZone = strings.TrimPrefix(timeZone, "-")
triggerDate, err := time.Parse(layout, startDate)
if err != nil {
log.Error("Error parsing time err: ", err.Error())
}
log.Debug("Time parsed from settings: ", triggerDate)
var hour int
var minutes int
sliceArray := strings.Split(timeZone, ":")
if len(sliceArray) != 2 {
log.Error("Time zone has wrong format: ", timeZone)
} else {
hour, _ = strconv.Atoi(sliceArray[0])
minutes, _ = strconv.Atoi(sliceArray[1])
log.Debug("Duration hour: ", time.Duration(hour)*time.Hour)
log.Debug("Duration minutes: ", time.Duration(minutes)*time.Minute)
}
hours, _ := strconv.Atoi(timeZone)
log.Debug("hours: ", hours)
if isNegative {
log.Debug("Adding to triggerDate")
triggerDate = triggerDate.Add(time.Duration(hour) * time.Hour)
triggerDate = triggerDate.Add(time.Duration(minutes) * time.Minute)
} else {
log.Debug("Subtracting to triggerDate")
triggerDate = triggerDate.Add(time.Duration(hour * -1))
triggerDate = triggerDate.Add(time.Duration(minutes))
}
currentTime := time.Now().UTC()
log.Debug("Current time: ", currentTime)
log.Debug("Setting start time: ", triggerDate)
duration := time.Since(triggerDate)
durSeconds := duration.Seconds()
if durSeconds < 0 {
//Future date
return int(math.Abs(durSeconds))
} else {
// Past date
return 0
}
}
type PrintJob struct {
Msg string
}
func (j *PrintJob) Run() error {
log.Debug(j.Msg)
return nil
}
func (t *TimerTrigger) scheduleJobEverySecond(tgrHandler *trigger.Handler, notImmediately bool, fn func()) *scheduler.Job {
var interval int = 0
if seconds := tgrHandler.GetStringSetting("seconds"); seconds != "" {
seconds, _ := strconv.Atoi(seconds)
interval = interval + seconds
}
if minutes := tgrHandler.GetStringSetting("minutes"); minutes != "" {
minutes, _ := strconv.Atoi(minutes)
interval = interval + minutes*60
}
if hours := tgrHandler.GetStringSetting("hours"); hours != "" {
hours, _ := strconv.Atoi(hours)
interval = interval + hours*3600
}
log.Debug("Repeating seconds: ", interval)
// schedule repeating
var timerJob *scheduler.Job
var err error
if notImmediately {
timerJob, err = scheduler.Every(interval).Seconds().NotImmediately().Run(fn)
if err != nil {
log.Error("Error scheduleRepeating (repeat seconds) flo err: ", err.Error())
}
} else {
timerJob, err = scheduler.Every(interval).Seconds().Run(fn)
if err != nil {
log.Error("Error scheduleRepeating (repeat seconds) flo err: ", err.Error())
}
}
if timerJob == nil {
log.Error("timerJob is nil")
}
t.timers = append(t.timers, timerJob)
return timerJob
}