Skip to content

Commit aede2cc

Browse files
committed
Add an optional argument to Backoff policy - max delay. This caps the maximum wait time waited between retries.
1 parent f912c91 commit aede2cc

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed

src/main/scala/Defaults.scala

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,6 @@ import java.util.concurrent.TimeUnit
55

66
object Defaults {
77
val delay: FiniteDuration = Duration(500, TimeUnit.MILLISECONDS)
8+
val maxDelay: Duration = Duration.Inf
89
}
910

src/main/scala/Policy.scala

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -77,9 +77,14 @@ object Pause {
7777
}
7878

7979
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+
}
8085

8186
/** 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)
8388
(implicit timer: Timer): Policy =
8489
new Policy {
8590
def apply[T]
@@ -88,7 +93,7 @@ object Backoff {
8893
executor: ExecutionContext): Future[T] = {
8994
def run(delay: FiniteDuration): Future[T] = retry(promise, { () =>
9095
Delay(delay) {
91-
run(Duration(delay.length * base, delay.unit))
96+
run(nextDelay(delay * base, maxDelay))
9297
}.future.flatMap(identity)
9398
})
9499
run(delay)
@@ -99,7 +104,8 @@ object Backoff {
99104
def apply(
100105
max: Int = 8,
101106
delay: FiniteDuration = Defaults.delay,
102-
base: Int = 2)
107+
base: Int = 2,
108+
maxDelay: Duration = Defaults.maxDelay)
103109
(implicit timer: Timer): Policy =
104110
new CountingPolicy {
105111
def apply[T]
@@ -109,7 +115,7 @@ object Backoff {
109115
def run(max: Int, delay: FiniteDuration): Future[T] = countdown(
110116
max, promise,
111117
count => Delay(delay) {
112-
run(count, Duration(delay.length * base, delay.unit))
118+
run(count, nextDelay(delay * base, maxDelay))
113119
}.future.flatMap(identity))
114120
run(max, delay)
115121
}

0 commit comments

Comments
 (0)