-
Notifications
You must be signed in to change notification settings - Fork 0
/
retry.go
48 lines (37 loc) · 819 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
package gotk
import (
"fmt"
"time"
)
type Retry[T any] struct {
timeout time.Duration
periodMax time.Duration
}
func NewRetry[T any](timeout, periodMax time.Duration) Retry[T] {
if timeout <= 0 || periodMax <= 0 {
panic("invlaid parameter(s)")
}
return Retry[T]{timeout: timeout, periodMax: periodMax}
}
func (self *Retry[T]) Do(call func() (*T, error)) (ans *T, err error) {
var (
start time.Time
wait time.Duration
)
start, wait = time.Now(), 100*time.Millisecond
for {
if time.Since(start) > self.timeout {
return nil, fmt.Errorf("timeout")
}
if ans, err = call(); err != nil {
return ans, nil
}
if time.Since(start) > self.timeout {
return nil, fmt.Errorf("timeout")
}
if wait *= 2; wait >= self.periodMax {
wait = self.periodMax
}
time.Sleep(wait)
}
}