-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_test.go
More file actions
249 lines (189 loc) · 4.99 KB
/
example_test.go
File metadata and controls
249 lines (189 loc) · 4.99 KB
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
//nolint:errcheck,gosec // examples prioritize clarity over exhaustive error handling
package cron_test
import (
"context"
"errors"
"fmt"
"log/slog"
"os"
"sync/atomic"
"time"
"github.com/hyp3rd/cron/v4"
)
const (
exampleEverySecond = "* * * * * *"
exampleEveryHour = "0 * * * *"
exampleNextNCount = 3
)
var errAttemptFailed = errors.New("attempt failed")
func ExampleCron_AddFunc() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cronInstance := cron.New(cron.WithSeconds())
cronInstance.AddFunc(exampleEverySecond, func(_ context.Context) error {
fmt.Println("tick")
cancel()
return nil
})
cronInstance.Start(ctx)
<-ctx.Done()
cronInstance.Stop(context.Background())
// Output:
// tick
}
func ExampleCron_AddNamedFunc() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cronInstance := cron.New(cron.WithSeconds())
cronInstance.AddNamedFunc("heartbeat", exampleEverySecond, func(_ context.Context) error {
fmt.Println("heartbeat")
cancel()
return nil
})
entry := cronInstance.Entries()[0]
fmt.Println("name:", entry.Name)
cronInstance.Start(ctx)
<-ctx.Done()
cronInstance.Stop(context.Background())
// Output:
// name: heartbeat
// heartbeat
}
func ExampleCron_Shutdown() {
cronInstance := cron.New(cron.WithSeconds())
done := make(chan struct{})
cronInstance.AddFunc(exampleEverySecond, func(_ context.Context) error {
fmt.Println("tick")
close(done)
return nil
})
cronInstance.Start(context.Background())
<-done
cronInstance.Shutdown(context.Background())
fmt.Println("graceful stop")
// Output:
// tick
// graceful stop
}
func ExampleNextN() {
sched, _ := cron.ParseStandard(exampleEveryHour)
//nolint:revive // example uses fixed date for deterministic output
anchor := time.Date(2024, 6, 3, 12, 0, 0, 0, time.UTC)
times := cron.NextN(sched, anchor, exampleNextNCount)
for _, nextTime := range times {
fmt.Println(nextTime.Format(time.DateTime))
}
// Output:
// 2024-06-03 13:00:00
// 2024-06-03 14:00:00
// 2024-06-03 15:00:00
}
func ExampleSpecSchedule_String() {
parser := cron.NewSpecParser(
cron.Second | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor,
)
sched, _ := parser.Parse("*/5 * * * * *")
fmt.Println(sched)
// Output:
// 0,5,10,15,20,25,30,35,40,45,50,55 * * * * *
}
func ExampleTimeout() {
job := cron.NewChain(cron.Timeout(5 * time.Second)).Then(
cron.FuncJob(func(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(time.Millisecond):
fmt.Println("done")
return nil
}
}),
)
job.Run(context.Background())
// Output:
// done
}
func ExampleRecover() {
job := cron.NewChain(cron.Recover(cron.DiscardLogger())).Then(
cron.FuncJob(func(_ context.Context) error {
panic("boom")
}),
)
err := job.Run(context.Background())
fmt.Println(errors.Is(err, cron.ErrPanic))
// Output:
// true
}
func ExampleMaxConcurrent() {
logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
job := cron.NewChain(cron.MaxConcurrent(2, logger)).Then(
cron.FuncJob(func(_ context.Context) error {
fmt.Println("running")
return nil
}),
)
job.Run(context.Background())
// Output:
// running
}
func ExampleRetryOnError() {
var attempts atomic.Int32
job := cron.NewChain(cron.RetryOnError(2, time.Millisecond)).Then(
cron.FuncJob(func(_ context.Context) error {
attempt := attempts.Add(1)
if attempt < 3 {
return fmt.Errorf("%w: %d", errAttemptFailed, attempt)
}
fmt.Println("succeeded on attempt", attempt)
return nil
}),
)
job.Run(context.Background())
// Output:
// succeeded on attempt 3
}
func ExampleWithEventHooks() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cronInstance := cron.New(
cron.WithSeconds(),
cron.WithEventHooks(cron.EventHooks{
OnJobStart: func(id cron.EntryID, name string) {
fmt.Printf("start: %s (id=%d)\n", name, id)
},
OnJobComplete: func(id cron.EntryID, name string, _ time.Duration, _ error) {
fmt.Printf("complete: %s (id=%d)\n", name, id)
cancel()
},
}),
)
cronInstance.AddNamedFunc("hello", exampleEverySecond, func(_ context.Context) error {
return nil
})
cronInstance.Start(ctx)
<-ctx.Done()
cronInstance.Stop(context.Background())
// Output:
// start: hello (id=1)
// complete: hello (id=1)
}
func ExampleWithOnError() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cronInstance := cron.New(
cron.WithSeconds(),
cron.WithLogger(cron.DiscardLogger()),
cron.WithOnError(func(id cron.EntryID, name string, err error) {
fmt.Printf("error in %s (id=%d): %v\n", name, id, err)
cancel()
}),
)
cronInstance.AddNamedFunc("failing-job", exampleEverySecond, func(_ context.Context) error {
return errors.New("something went wrong") //nolint:err113 // example error
})
cronInstance.Start(ctx)
<-ctx.Done()
cronInstance.Stop(context.Background())
// Output:
// error in failing-job (id=1): something went wrong
}