-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathschedule.go
80 lines (70 loc) · 1.64 KB
/
schedule.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
package workers
import (
"context"
"time"
"github.com/robfig/cron"
)
// ScheduleFunc is job wrapper for implement job run schedule
type ScheduleFunc func(context.Context, Job) Job
// ByTimer returns job wrapper func for run job each period duration
// after previous run completed
func ByTimer(period time.Duration) ScheduleFunc {
return func(ctx context.Context, j Job) Job {
return func(ctx context.Context) {
timer := time.NewTimer(period)
defer timer.Stop()
for {
select {
case <-ctx.Done():
return
case <-timer.C:
j(ctx)
timer.Reset(period)
}
}
}
}
}
// ByTicker returns func which run Worker by ticker each period duration
func ByTicker(period time.Duration) ScheduleFunc {
return func(ctx context.Context, j Job) Job {
return func(ctx context.Context) {
ticker := time.NewTicker(period)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
j(ctx)
}
}
}
}
}
// ByCronSchedule returns job wrapper func for run job by cron schedule
// using robfig/cron parser for parse cron spec.
// If schedule spec not valid throw panic, shit happens.
func ByCronSchedule(schedule string) ScheduleFunc {
s, err := cron.Parse(schedule)
if err != nil {
panic("parse cron spec fatal error: " + err.Error())
}
return func(ctx context.Context, job Job) Job {
return func(ctx context.Context) {
now := time.Now()
timer := time.NewTimer(s.Next(now).Sub(now))
defer timer.Stop()
for {
select {
case <-ctx.Done():
return
case <-timer.C:
job(ctx)
now = time.Now()
timer.Reset(s.Next(now).Sub(now))
}
}
}
}
}