-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathretry.go
64 lines (53 loc) · 1.22 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
package gokit
import (
"context"
"errors"
"time"
)
// Retry 重试执行,最多不超过指定次数,每次间隔固定时长
func Retry(ctx context.Context, count int, wait time.Duration, fn func() error) error {
return retry(ctx, count, wait, false, fn)
}
// BackoffRetry 重试执行,最多不超过指定次数,每次间隔时长翻倍
func BackoffRetry(ctx context.Context, count int, wait time.Duration, fn func() error) error {
return retry(ctx, count, wait, true, fn)
}
func retry(ctx context.Context, count int, wait time.Duration, backoff bool, fn func() error) (err error) {
if count <= 0 {
return errors.New("invalid retry count")
}
var errs []error
tryExecute := func(wait time.Duration) (err error) {
defer func() {
if err != nil {
errs = append(errs, err)
}
}()
select {
case <-ctx.Done():
return ctx.Err()
default:
if wait == 0 {
return fn()
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(wait):
return fn()
}
}
}
if err = tryExecute(0); err == nil {
return
}
for i, c := 0, count-1; i < c; i++ {
if err = tryExecute(wait); err == nil {
return
}
if backoff {
wait = wait * 2
}
}
return errors.Join(errs...)
}