forked from mmaxiaolei/backoff
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexponential.go
More file actions
84 lines (73 loc) · 1.7 KB
/
Copy pathexponential.go
File metadata and controls
84 lines (73 loc) · 1.7 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
package backoff
import (
"math"
"math/rand"
"time"
)
const (
defaultMinInterval = 500 * time.Millisecond
defaultMaxInterval = 1 * time.Minute
defaultFactor = 1.5
defaultJitterFactor = 0.5
)
type Exponential struct {
minInterval time.Duration
maxInterval time.Duration
factor float64
jitterFactor float64 // 0<jitterFactor<1
attempts float64
}
type ExponentialOption func(exponential *Exponential)
func NewExponentialBackoff(opts ...ExponentialOption) *Exponential {
e := &Exponential{
minInterval: defaultMinInterval,
maxInterval: defaultMaxInterval,
factor: defaultFactor,
jitterFactor: defaultJitterFactor,
attempts: 0,
}
for _, opt := range opts {
opt(e)
}
return e
}
func WithMinInterval(duration time.Duration) ExponentialOption {
return func(e *Exponential) {
e.minInterval = duration
}
}
func WithMaxInterval(duration time.Duration) ExponentialOption {
return func(e *Exponential) {
e.maxInterval = duration
}
}
func WithFactor(factor float64) ExponentialOption {
return func(e *Exponential) {
e.factor = factor
}
}
func WithJitterFactor(jitterFactor float64) ExponentialOption {
return func(e *Exponential) {
if jitterFactor > 1 {
jitterFactor = defaultJitterFactor
}
e.jitterFactor = jitterFactor
}
}
func (e *Exponential) Reset() {
e.attempts = 0
}
func (e *Exponential) Next() time.Duration {
current := float64(e.minInterval) * math.Pow(e.factor, e.attempts)
if current > float64(e.maxInterval) {
current = float64(e.maxInterval)
}
if e.jitterFactor > 0 {
j := e.jitterFactor * current
min := current - j
max := current + j
current = min + rand.Float64()*(max-min+1)
}
e.attempts++
return time.Duration(current)
}