@@ -77,9 +77,14 @@ object Pause {
7777}
7878
7979object 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