forked from mcuadros/ofelia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscheduler.go
122 lines (94 loc) · 2.04 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
package core
import (
"errors"
"fmt"
"sync"
"github.com/robfig/cron"
)
var (
ErrEmptyScheduler = errors.New("unable to start a empty scheduler.")
ErrEmptySchedule = errors.New("unable to add a job with a empty schedule.")
)
type Scheduler struct {
Jobs []Job
Logger Logger
middlewareContainer
cron *cron.Cron
wg sync.WaitGroup
isRunning bool
}
func NewScheduler(l Logger) *Scheduler {
return &Scheduler{
Logger: l,
cron: cron.New(),
}
}
func (s *Scheduler) AddJob(j Job) error {
s.Logger.Noticef("New job registered %q - %q - %q", j.GetName(), j.GetCommand(), j.GetSchedule())
if j.GetSchedule() == "" {
return ErrEmptySchedule
}
err := s.cron.AddJob(j.GetSchedule(), &jobWrapper{s, j})
if err != nil {
return err
}
s.Jobs = append(s.Jobs, j)
return nil
}
func (s *Scheduler) Start() error {
if len(s.Jobs) == 0 {
return ErrEmptyScheduler
}
s.Logger.Debugf("Starting scheduler with %d jobs", len(s.Jobs))
s.mergeMiddlewares()
s.isRunning = true
s.cron.Start()
return nil
}
func (s *Scheduler) mergeMiddlewares() {
for _, j := range s.Jobs {
j.Use(s.Middlewares()...)
}
}
func (s *Scheduler) Stop() error {
s.wg.Wait()
s.cron.Stop()
s.isRunning = false
return nil
}
func (s *Scheduler) IsRunning() bool {
return s.isRunning
}
type jobWrapper struct {
s *Scheduler
j Job
}
func (w *jobWrapper) Run() {
w.s.wg.Add(1)
defer w.s.wg.Done()
e := NewExecution()
ctx := NewContext(w.s, w.j, e)
w.start(ctx)
err := ctx.Next()
w.stop(ctx, err)
}
func (w *jobWrapper) start(ctx *Context) {
ctx.Start()
ctx.Log("Started - " + ctx.Job.GetCommand())
}
func (w *jobWrapper) stop(ctx *Context, err error) {
ctx.Stop(err)
errText := "none"
if ctx.Execution.Error != nil {
errText = ctx.Execution.Error.Error()
}
output := ctx.Execution.OutputStream.Bytes()
if len(output) > 0 {
ctx.Log("Output: " + string(output))
}
msg := fmt.Sprintf(
"Finished in %q, failed: %t, skipped: %t, error: %s",
ctx.Execution.Duration, ctx.Execution.Failed, ctx.Execution.Skipped, errText,
)
ctx.Log(msg)
}