forked from chaseisabelle/backoff
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackoff.go
64 lines (49 loc) · 1.03 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 backoff
import (
"errors"
"sync"
"time"
)
type Backoff struct {
sync.Mutex
initial uint64
current uint64
max uint64
algo func(uint64) uint64
}
func New(initial uint64, current uint64, max uint64, algo func(uint64) uint64) (*Backoff, error) {
if initial > max {
return nil, errors.New("initial cant be greater than max")
}
if current > max {
return nil, errors.New("current cant be greater than max")
}
if algo == nil {
if initial != current || current != max {
return nil, errors.New("initial, current, and max must be equal for flat backoff")
}
algo = func(current uint64) uint64 {
return current
}
}
return &Backoff{
initial: initial,
current: current,
max: max,
algo: algo,
}, nil
}
func (bo *Backoff) Backoff() {
bo.Lock()
defer bo.Unlock()
time.Sleep(time.Duration(bo.current) * time.Millisecond)
bo.current = bo.algo(bo.current)
if bo.current > bo.max {
bo.current = bo.max
}
}
func (bo *Backoff) Reset() {
bo.Lock()
defer bo.Unlock()
bo.current = bo.initial
}