-
Notifications
You must be signed in to change notification settings - Fork 0
/
retry.go
86 lines (79 loc) · 2.1 KB
/
retry.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
package retry
import (
"context"
"time"
)
// Retry retries the given callback at max the given number of times.
// It stops as soon as a `nil` error is returned.
func Retry(numTimes int, cb func() error) error {
var err error
for i := 0; i <= numTimes; i++ {
err = cb()
if err == nil {
break
}
}
return err
}
// RetryCtx retries the given callback at max the given number of times.
// It stops as soon as a `nil` error is returned.
func RetryCtx(ctx context.Context, numTimes int, cb func() error) error {
return Retry(numTimes, func() error {
if ctx.Err() != nil {
return ctx.Err()
}
return cb()
})
}
// RetryWithDelay retries the given callback at max the given number of times.
// It stops as soon as a `nil` error is returned.
// It sleeps for the given delay if an error happens.
func RetryWithDelay(numTimes int, delay time.Duration, cb func() error) error {
var err error
for i := 0; i <= numTimes; i++ {
err = cb()
if err == nil {
break
}
time.Sleep(delay)
}
return err
}
// RetryWithDelayCtx retries the given callback at max the given number of times.
// It stops as soon as a `nil` error is returned.
// It sleeps for the given delay if an error happens.
func RetryWithDelayCtx(ctx context.Context, numTimes int, delay time.Duration, cb func() error) error {
return RetryWithDelay(numTimes, delay, func() error {
if ctx.Err() != nil {
return ctx.Err()
}
return cb()
})
}
// RetryWithStop retries the given callback at max the given number of times.
// It stops only when `stop` is called.
func RetryWithStop(numTimes int, cb func(stop func()) error) error {
var err error
var cancelled bool
stop := func() {
cancelled = true
}
for i := 0; i <= numTimes; i++ {
if cancelled {
break
}
err = cb(stop)
}
return err
}
// RetryWithStopCtx retries the given callback at max the given number of times.
// It stops only when `stop` is called.
func RetryWithStopCtx(ctx context.Context, numTimes int, cb func(stop func()) error) error {
return RetryWithStop(numTimes, func(stop func()) error {
if ctx.Err() != nil {
stop()
return ctx.Err()
}
return cb(stop)
})
}