@@ -77,9 +77,14 @@ object Pause {
77
77
}
78
78
79
79
object Backoff {
80
+ private def nextDelay (calculatedDelay : FiniteDuration , maxDelay : Duration ): FiniteDuration =
81
+ maxDelay match {
82
+ case _ : Duration .Infinite => calculatedDelay
83
+ case delay : FiniteDuration => List (calculatedDelay, delay).min
84
+ }
80
85
81
86
/** Retry with exponential backoff forever */
82
- def forever (delay : FiniteDuration = Defaults .delay, base : Int = 2 )
87
+ def forever (delay : FiniteDuration = Defaults .delay, base : Int = 2 , maxDelay : Duration = Defaults .maxDelay )
83
88
(implicit timer : Timer ): Policy =
84
89
new Policy {
85
90
def apply [T ]
@@ -88,7 +93,7 @@ object Backoff {
88
93
executor : ExecutionContext ): Future [T ] = {
89
94
def run (delay : FiniteDuration ): Future [T ] = retry(promise, { () =>
90
95
Delay (delay) {
91
- run(Duration (delay.length * base, delay.unit ))
96
+ run(nextDelay (delay * base, maxDelay ))
92
97
}.future.flatMap(identity)
93
98
})
94
99
run(delay)
@@ -99,7 +104,8 @@ object Backoff {
99
104
def apply (
100
105
max : Int = 8 ,
101
106
delay : FiniteDuration = Defaults .delay,
102
- base : Int = 2 )
107
+ base : Int = 2 ,
108
+ maxDelay : Duration = Defaults .maxDelay)
103
109
(implicit timer : Timer ): Policy =
104
110
new CountingPolicy {
105
111
def apply [T ]
@@ -109,7 +115,7 @@ object Backoff {
109
115
def run (max : Int , delay : FiniteDuration ): Future [T ] = countdown(
110
116
max, promise,
111
117
count => Delay (delay) {
112
- run(count, Duration (delay.length * base, delay.unit ))
118
+ run(count, nextDelay (delay * base, maxDelay ))
113
119
}.future.flatMap(identity))
114
120
run(max, delay)
115
121
}
0 commit comments