-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscheduler.go
91 lines (73 loc) · 1.46 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
package goschedtask
import (
"reflect"
"time"
"golang.org/x/exp/slices"
)
type Scheduler struct {
Jobs []Job
}
var (
mainScheduler = NewScheduler()
)
func (Sched Scheduler) RunJobs() chan bool {
mainScheduler.Jobs = Jobs
mainScheduler.SetFirstTimeRun()
tick := time.NewTicker(time.Second * 1)
stopped := make(chan bool)
go func() {
for {
select {
case <-tick.C:
mainScheduler.RunPendingJobs()
case <-stopped:
return
}
}
}()
return stopped
}
func (Sched *Scheduler) RunPendingJobs() {
for i, j := range Sched.Jobs {
if j.MustDeleted {
Sched.Jobs = slices.Delete(Sched.Jobs, i, i+1)
continue
}
if ShouldRun(j.TimeRun) {
go RunJobWithParam(j.JobFunc, j.JobParams)
Sched.Jobs[i].TimeRun = Sched.Jobs[i].TimeRun.Add(Sched.Jobs[i].Interval)
if !j.RunLoop {
Sched.Jobs[i].MustDeleted = true
}
}
}
}
func (Sched Scheduler) SetFirstTimeRun() {
for i, j := range Sched.Jobs {
if j.Interval.Seconds() != 0 {
Sched.Jobs[i].TimeRun = time.Now().Add(j.Interval)
}
}
}
func NewScheduler() Scheduler {
return Scheduler{
Jobs: []Job{},
}
}
func ShouldRun(t time.Time) bool {
if time.Now().After(t) {
return true
}
return false
}
func RunJobWithParam(jobFunc interface{}, params []interface{}) {
j := reflect.ValueOf(jobFunc)
in := make([]reflect.Value, len(params))
for k, param := range params {
in[k] = reflect.ValueOf(param)
}
j.Call(in)
}
func RunJobs() chan bool {
return mainScheduler.RunJobs()
}