-
Notifications
You must be signed in to change notification settings - Fork 0
/
periodic.go
118 lines (107 loc) · 2.54 KB
/
periodic.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
package goscript
import (
"github.com/adhocore/gronx"
"time"
)
// Periodic is the list of cron expressions to run periodically
type Periodic []string
// Periodics is a helper function to add multiple strings without needing a []string{}
func Periodics(times ...string) []string {
rtn := make([]string, len(times))
//TODO: Validate the cron strings
copy(rtn, times)
return rtn
}
func (gs *GoScript) runPeriodic() {
// TODO: Validate Periodic slice
// run zero length immediate periodics and delete from periodic list
for _, triggers := range gs.periodic {
for _, t := range triggers {
for i := range t.Periodic {
if len(t.Periodic[i]) == 0 {
task := gs.newTask(t, nil)
gs.taskToRun.add(task)
t.Periodic = append(t.Periodic[:i], t.Periodic[i+1:]...)
}
}
}
}
delete(gs.periodic, "")
// setup the next fire time for all triggers
gs.fillNextTime()
ticker := time.NewTicker(time.Second)
for {
select {
case <-ticker.C:
if time.Now().After(gs.nextPeriodic) {
go gs.shouldRunTrigger()
}
case <-gs.ctx.Done():
return
}
}
}
func (gs *GoScript) shouldRunTrigger() {
gs.nextPeriodic = time.Now().Add(60 * time.Minute)
for _, triggers := range gs.periodic {
for _, t := range triggers {
if t.nextTime == nil {
gs.Logger().Info("next time not set")
_, err := t.NextTime(time.Now())
if err != nil {
gs.Logger().Error(err, "setting next time failed")
continue
}
}
if time.Now().After(*t.nextTime) {
task := gs.newTask(t, nil)
gs.taskToRun.add(task)
_, err := t.NextTime(time.Now())
if err != nil {
gs.Logger().Error(err, "setting next time failed")
continue
}
}
if t.nextTime.Before(gs.nextPeriodic) {
gs.nextPeriodic = *t.nextTime
}
}
}
}
func (gs *GoScript) runGronJob(gron *gronx.Gronx, start bool) {
for expr, triggers := range gs.periodic {
var err error
var due bool
if len(expr) == 0 {
if start {
due = true
}
} else {
due, err = gron.IsDue(expr)
if err != nil {
gs.logger.Error(err, "gron job IsDue failed")
continue
}
}
for _, t := range triggers {
if due {
task := gs.newTask(t, nil)
gs.taskToRun.add(task)
}
}
}
}
func (gs *GoScript) fillNextTime() {
gs.nextPeriodic = time.Now().Add(60 * time.Minute)
for _, triggers := range gs.periodic {
for _, t := range triggers {
nt, err := t.NextTime(time.Now())
if err != nil {
gs.Logger().Error(err, "setting next time failed")
}
if nt != nil && nt.Before(gs.nextPeriodic) {
gs.nextPeriodic = *nt
}
}
}
}