forked from Axway/agent-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackoff.go
49 lines (42 loc) · 991 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
package jobs
import (
"sync"
"time"
)
func newBackoffTimeout(startingTimeout time.Duration, maxTimeout time.Duration, increaseFactor int) *backoff {
return &backoff{
base: startingTimeout,
max: maxTimeout,
current: startingTimeout,
factor: increaseFactor,
backoffMutex: &sync.Mutex{},
}
}
type backoff struct {
base time.Duration
max time.Duration
current time.Duration
factor int
backoffMutex *sync.Mutex
}
func (b *backoff) increaseTimeout() {
b.backoffMutex.Lock()
defer b.backoffMutex.Unlock()
b.current = b.current * time.Duration(b.factor)
if b.current > b.max {
b.current = b.base // reset to base timeout
}
}
func (b *backoff) reset() {
b.backoffMutex.Lock()
defer b.backoffMutex.Unlock()
b.current = b.base
}
func (b *backoff) sleep() {
time.Sleep(b.current)
}
func (b *backoff) getCurrentTimeout() time.Duration {
b.backoffMutex.Lock()
defer b.backoffMutex.Unlock()
return b.current
}