-
Notifications
You must be signed in to change notification settings - Fork 0
/
scheduler.go
93 lines (78 loc) · 1.66 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
package scheduler
import (
"errors"
"github.com/najibulloShapoatov/server-core/cluster"
"github.com/najibulloShapoatov/server-core/monitoring/log"
"github.com/robfig/cron/v3"
)
type Task struct {
Name string
Spec string
MaxRetry int
Job ScheduleFunc
Cluster *cluster.Cluster
entryID cron.EntryID
}
type ScheduleFunc func() error
var scheduler = newCron()
func newCron() *cron.Cron {
c := cron.New(cron.WithSeconds())
c.Start()
return c
}
// RegisterJob registers a new job
func RegisterJob(task *Task) error {
if task == nil {
return errors.New("please define a task")
}
job := func() {
err := runJob(task)
if err != nil {
log.Error(task.Name, err.Error())
} else {
log.Info("job success", task.Name)
}
}
entryID, err := scheduler.AddFunc(task.Spec, job)
task.entryID = entryID
return err
}
// UnregisterJob unregisters a job
func UnregisterJob(task *Task) error {
if task == nil {
return errors.New("please define a task")
}
scheduler.Remove(task.entryID)
return nil
}
func runJob(task *Task) error {
if task.Cluster == nil {
c, err := cluster.Join("scheduler")
if err != nil {
return runWithRetry(task, task.MaxRetry)
} else {
task.Cluster = c
return runOnCluster(task)
}
} else {
return runOnCluster(task)
}
}
func runWithRetry(task *Task, attempts int) error {
if err := task.Job(); err != nil {
if attempts--; attempts > 0 {
return runWithRetry(task, attempts)
}
return err
}
return nil
}
func runOnCluster(task *Task) error {
err := task.Cluster.Lock(task.Name)
if err == nil {
err = runWithRetry(task, task.MaxRetry)
_ = task.Cluster.Unlock(task.Name)
return err
}
return nil
}