-
Notifications
You must be signed in to change notification settings - Fork 71
/
retry.go
49 lines (42 loc) · 852 Bytes
/
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
package utils
import (
"context"
"time"
)
type Retry struct {
MaxRetries int
retryDelayMilliSec int
RetryFunc func() error
}
func NewRetry(maxRetries int, retryDelayMilliSec int, retryFunc func() error) *Retry {
return &Retry{
MaxRetries: maxRetries,
retryDelayMilliSec: retryDelayMilliSec,
RetryFunc: retryFunc,
}
}
func (r *Retry) ExecWithRetries(ctx context.Context) error {
tries := 0
success := false
for !success {
tries++
if err := r.RetryFunc(); err != nil {
if tries == r.MaxRetries {
return err
}
w := make(chan struct{}, 1)
go func() {
time.Sleep(time.Duration(r.retryDelayMilliSec) * time.Millisecond)
w <- struct{}{}
}()
select {
case <-ctx.Done():
return context.Canceled
case <-w:
}
} else {
success = true
}
}
return nil
}