-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscheduler.go
206 lines (189 loc) · 4.1 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
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
package cronjob
import (
"fmt"
"runtime/debug"
"sync"
"time"
)
// Job represents a job to be run.
type Job struct {
Schedule *CronExpression
Task func()
}
// CronScheduler represents a cron job scheduler.
type CronScheduler struct {
Jobs []*Job
mutex sync.Mutex
running bool
stop chan struct{}
}
// NewCronScheduler creates a new CronScheduler.
func NewCronScheduler() *CronScheduler {
return &CronScheduler{
Jobs: make([]*Job, 0),
}
}
// AddJob adds a new job to the scheduler.
func (c *CronScheduler) AddJob(expr string, task func()) error {
schedule, err := ParseCronExpression(expr)
if err != nil {
return err
}
job := &Job{
Schedule: schedule,
Task: task,
}
c.mutex.Lock()
c.Jobs = append(c.Jobs, job)
c.mutex.Unlock()
return nil
}
// RemoveJob removes a job from the scheduler by index.
func (c *CronScheduler) RemoveJob(index int) error {
c.mutex.Lock()
defer c.mutex.Unlock()
if index < 0 || index >= len(c.Jobs) {
return fmt.Errorf("index out of range")
}
c.Jobs = append(c.Jobs[:index], c.Jobs[index+1:]...)
return nil
}
// Start starts the scheduler.
func (c *CronScheduler) Start() {
c.mutex.Lock()
if c.running {
c.mutex.Unlock()
return
}
c.running = true
if c.stop == nil {
c.stop = make(chan struct{})
}
c.mutex.Unlock()
go func() {
for {
now := time.Now()
c.mutex.Lock()
if !c.running {
c.mutex.Unlock()
return
}
c.mutex.Unlock()
nextRun := c.timeUntilNextJob(now)
if nextRun <= 0 {
// Run due jobs immediately
c.runDueJobs(now)
continue
}
timer := time.NewTimer(nextRun)
select {
case <-timer.C:
c.runDueJobs(time.Now())
case <-c.stop:
timer.Stop()
return
}
}
}()
}
// Stop stops the scheduler.
func (c *CronScheduler) Stop() {
c.mutex.Lock()
if c.running {
c.running = false
close(c.stop)
c.stop = nil
}
c.mutex.Unlock()
}
func nextRunTime(expr *CronExpression, fromTime time.Time) time.Time {
// Start from the next minute
nextTime := fromTime.Add(time.Minute - time.Duration(fromTime.Second())*time.Second - time.Duration(fromTime.Nanosecond()))
// Limit to prevent infinite loops in case of errors
maxIterations := 1000000
for i := 0; i < maxIterations; i++ {
if isTimeMatching(expr, nextTime) {
return nextTime
}
nextTime = nextTime.Add(time.Minute)
}
// If we exceed maxIterations, return zero time
return time.Time{}
}
func (c *CronScheduler) runDueJobs(now time.Time) {
c.mutex.Lock()
jobsToRun := make([]*Job, 0)
for _, job := range c.Jobs {
if isTimeMatching(job.Schedule, now) {
jobsToRun = append(jobsToRun, job)
}
}
c.mutex.Unlock()
for _, job := range jobsToRun {
go func(job *Job) {
defer func() {
if r := recover(); r != nil {
// Log the panic with stack trace
fmt.Printf("Task panicked: %v\nStack trace:\n%s\n", r, debug.Stack())
}
}()
job.Task()
}(job)
}
}
func (c *CronScheduler) timeUntilNextJob(now time.Time) time.Duration {
c.mutex.Lock()
defer c.mutex.Unlock()
minDuration := time.Hour * 24 * 365 // 1 year
for _, job := range c.Jobs {
nextRun := nextRunTime(job.Schedule, now)
if nextRun.IsZero() {
continue
}
duration := nextRun.Sub(now)
if duration < minDuration {
minDuration = duration
}
}
return minDuration
}
// ListJobs lists all jobs in the scheduler.
func (c *CronScheduler) ListJobs() []string {
c.mutex.Lock()
defer c.mutex.Unlock()
var jobList []string
for i, job := range c.Jobs {
jobList = append(jobList, fmt.Sprintf("Job %d: %v", i, job.Schedule))
}
return jobList
}
func isTimeMatching(expr *CronExpression, t time.Time) bool {
if !contains(expr.Minutes, t.Minute()) {
return false
}
if !contains(expr.Hours, t.Hour()) {
return false
}
if !contains(expr.DayOfMonth, t.Day()) {
return false
}
if !contains(expr.Month, int(t.Month())) {
return false
}
weekday := int(t.Weekday())
if weekday == 0 {
weekday = 7 // Adjust for Sunday=0 in Go but 7 in cron
}
if !contains(expr.DayOfWeek, weekday%7) {
return false
}
return true
}
func contains(list []int, value int) bool {
for _, v := range list {
if v == value {
return true
}
}
return false
}