forked from crow-misia/go-push-receiver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackoff.go
49 lines (41 loc) · 888 Bytes
/
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
/*
* Copyright (c) 2019 Zenichi Amano
*
* This file is part of go-push-receiver, which is MIT licensed.
* See http://opensource.org/licenses/MIT
*/
package pushreceiver
import (
"math/rand"
"time"
)
// Backoff with jitter sleep to prevent overloaded conditions during intervals
// https://www.awsarchitectureblog.com/2015/03/backoff.html
type Backoff struct {
attempts int
base int64
max int64
}
// NewBackoff creates Backoff instance.
func NewBackoff(base time.Duration, max time.Duration) *Backoff {
return &Backoff{
attempts: 0,
base: int64(base),
max: int64(max),
}
}
func (b *Backoff) duration() time.Duration {
b.attempts++
n := 1 << uint(b.attempts) * b.base
if n < 0 {
n = 0
}
duration := rand.Int63n(n)
if duration > b.max {
duration = b.max
}
return time.Duration(duration)
}
func (b *Backoff) reset() {
b.attempts = 0
}