-
Notifications
You must be signed in to change notification settings - Fork 2
/
backoff.go
55 lines (50 loc) · 1.38 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
package retry
import "time"
// BackoffFunc is a function that maps the retry attempt
// to a delay (in seconds)
type BackoffFunc func(attempt uint) (delay time.Duration)
// ExponentialBackoff makes an immediate attempt
// and then backs off exponentially. I.e:
//
// For a seed delay of 5 seconds:
// Attempt 0 - delay 0 seconds
// Attempt 1 - delay 5 seconds
// Attempt 2 - delay 10 seconds
// Attempt 3 - delay 20 seconds
func ExponentialBackoff(seedDelay time.Duration) BackoffFunc {
return func(attempt uint) time.Duration {
if attempt == 0 {
return 0
}
return seedDelay << (attempt - 1)
}
}
// LinearBackoff makes an immediate attempt
// and then backs off linearly. I.e:
//
// For a seed delay of 5 seconds:
// Attempt 0 - delay 0 seconds
// Attempt 1 - delay 5 seconds
// Attempt 2 - delay 10 seconds
// Attempt 3 - delay 15 seconds
func LinearBackoff(seedDelay time.Duration) BackoffFunc {
return func(attempt uint) time.Duration {
return seedDelay * time.Duration(attempt)
}
}
// ConstantBackoff makes an immediate attempt
// and then backs off linearly. I.e:
//
// For a seed delay of 5 seconds:
// Attempt 0 - delay 0 seconds
// Attempt 1 - delay 5 seconds
// Attempt 2 - delay 5 seconds
// Attempt 3 - delay 5 seconds
func ConstantBackoff(seedDelay time.Duration) BackoffFunc {
return func(attempt uint) time.Duration {
if attempt == 0 {
return 0
}
return seedDelay
}
}