-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackoff.go
64 lines (61 loc) · 1.06 KB
/
backoff.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 main
import (
"context"
"fmt"
"time"
)
func expBackoff(
ctx context.Context,
call func() error,
limit int,
delay time.Duration,
multiplier float64,
) error {
result := make(chan error, 1)
done := ctx.Done()
go func() {
if limit < 1 || multiplier < 1.0 || delay == 0 {
result <- fmt.Errorf(
`want: limit>=1 got: limit=%d want: multiplier>=1.0 got: multiplier=%v want: delay>0 got: delay=%v`,
limit, multiplier, delay,
)
return
}
select {
case <-done:
return
default:
}
err := call()
if err == nil || limit == 1 {
result <- err
return
}
timer := time.NewTimer(delay)
for step, fDelay := 2, float64(delay); ; step++ {
select {
case <-done:
timer.Stop()
return
case <-timer.C:
err = call()
if err == nil || step == limit {
result <- err
return
}
}
fDelay *= multiplier
timer.Reset(time.Duration(fDelay))
}
}()
select {
case <-done:
return ctx.Err()
case err := <-result:
return err
}
}
func main() {
fmt.Println("Hello, 世界")
// TODO meaningful test logic
}