-
Notifications
You must be signed in to change notification settings - Fork 0
/
cron.go
144 lines (127 loc) · 2.59 KB
/
cron.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
package rice
import (
"context"
"fmt"
"sync"
"time"
"github.com/robfig/cron/v3"
)
type Task func() error
type TaskContext func(ctx context.Context) error
type contextKey string
func TimerRun(ctx context.Context, tm time.Time, task ...Task) error {
timer := time.NewTimer(time.Until(tm))
defer timer.Stop()
select {
case <-timer.C:
for _, tk := range task {
err := tk()
if err != nil {
return err
}
}
return nil
case <-ctx.Done():
return nil
}
}
func TickerRun(ctx context.Context, d time.Duration, task ...Task) error {
for _, tk := range task {
err := tk()
if err != nil {
return err
}
}
ticker := time.NewTicker(d)
defer ticker.Stop()
for {
select {
case <-ticker.C:
for _, tk := range task {
err := tk()
if err != nil {
return err
}
}
case <-ctx.Done():
return nil
}
}
}
// TickerRunWithStartTimeContext 到达 tm 时间之后,开始以 tikcer 的方式执行 task
func TickerRunWithStartTimeContext(ctx context.Context, wg *sync.WaitGroup, tm time.Time, d time.Duration, task ...TaskContext) error {
now := time.Now()
for ; now.After(tm); tm = tm.Add(d) {
ctx = context.WithValue(ctx, contextKey("tm"), tm)
for _, tk := range task {
err := tk(ctx)
if err != nil {
return fmt.Errorf("%v have an error - %w", tm, err)
}
}
}
if wg != nil {
wg.Done()
}
timer := time.NewTimer(time.Until(tm))
defer timer.Stop()
select {
case <-timer.C:
ctx := context.WithValue(ctx, contextKey("tm"), time.Now())
err := TickerRunContext(ctx, d, task...)
return err
case <-ctx.Done():
return nil
}
}
// TickerRunContext 立即开始以 ticker 的方式执行 task
func TickerRunContext(ctx context.Context, d time.Duration, task ...TaskContext) error {
for _, tk := range task {
err := tk(ctx)
if err != nil {
return err
}
}
ticker := time.NewTicker(d)
defer ticker.Stop()
for {
select {
case <-ticker.C:
ctx := context.WithValue(ctx, contextKey("tm"), time.Now())
for _, tk := range task {
err := tk(ctx)
if err != nil {
return err
}
}
case <-ctx.Done():
return nil
}
}
}
func CronRun(ctx context.Context, corn string, task ...func()) error {
c := cron.New(cron.WithSeconds())
defer c.Stop()
for _, tk := range task {
_, err := c.AddFunc(corn, tk)
if err != nil {
return err
}
}
c.Start()
<-ctx.Done()
return nil
}
func CronRunM(ctx context.Context, corn string, task ...func()) error {
c := cron.New()
defer c.Stop()
for _, tk := range task {
_, err := c.AddFunc(corn, tk)
if err != nil {
return err
}
}
c.Start()
<-ctx.Done()
return nil
}