-
Notifications
You must be signed in to change notification settings - Fork 0
/
retry.go
72 lines (56 loc) · 1.01 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
package do
import (
"context"
"errors"
"time"
)
var (
ErrNilDoer = errors.New("f is nil")
)
type Doer = func(context.Context) (canRetry bool, err error)
// RetryWithTimes retry f tryTimes times if f failed
func RetryWithTimes(ctx context.Context, tryTimes int, f Doer) error {
if f == nil {
return ErrNilDoer
}
var err error
for i := 1; i <= tryTimes; i++ {
if canRetry, err1 := f(ctx); err1 != nil {
err = err1
if !canRetry {
return err
}
time.Sleep(time.Second * (1<<i - 1))
continue
}
err = nil
break
}
return err
}
// RetryWithDeadline retry f before d exceeds if f failed
func RetryWithDeadline(ctx context.Context, d time.Time, f Doer) error {
if f == nil {
return ErrNilDoer
}
var err error
var i = 1
for {
if canRetry, err1 := f(ctx); err1 != nil {
err = err1
if !canRetry {
return err
}
now := time.Now()
if now.After(d) {
break
}
time.Sleep(time.Second * (1<<i - 1))
i++
continue
}
err = nil
break
}
return err
}