forked from wal-g/wal-g
-
Notifications
You must be signed in to change notification settings - Fork 0
/
timer.go
43 lines (38 loc) · 1.02 KB
/
timer.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
package walg
import (
"math"
"math/rand"
"time"
)
// ExponentialTicker is used for exponential backoff
// for uploading to S3. If the max wait time is reached,
// retries will occur after max wait time intervals up to
// max retries.
type ExponentialTicker struct {
MaxRetries int
retries int
MaxWait float64
wait float64
}
// NewExpTicker creates a new ExponentialTicker with
// configurable max number of retries and max wait time.
func NewExpTicker(retries int, wait float64) *ExponentialTicker {
return &ExponentialTicker{
MaxRetries: retries,
MaxWait: wait,
}
}
// Update increases running count of retries by 1 and
// exponentially increases the wait time until the
// max wait time is reached.
func (et *ExponentialTicker) Update() {
if et.wait < et.MaxWait {
rand.Seed(time.Now().UTC().UnixNano())
et.wait = math.Exp2(float64(et.retries)) + rand.Float64()
}
et.retries++
}
// Sleep will wait in seconds.
func (et *ExponentialTicker) Sleep() {
time.Sleep(time.Duration(et.wait) * time.Second)
}