Reputation: 41
Using Scala, retry when the very first call fails until we receive a success response or max time limit (say the {2500 - "time is taken to execute first call"} ms) is reached.
I tried using atmos library but did not find the option to terminate the call once the max time limit is reached.
import scala.concurrent.duration._
import atmos.dsl._
implicit val retryPolicy = retryForever using constantBackoff { 0 millis }
In the above retry policy, we cannot restrict the max time limit to stop the retry process. Please help. Any other approach to achieve this functionality is also appreciated.
Upvotes: 1
Views: 169
Reputation: 40510
You don't need libraries for this.
def keepTrying[T](until: Deadline)(what: => T): Try[T] = Try {
what
} recoverWith {
case _ if until.hasTimeLeft => keepTrying(until)(what)
}
Note, you may want some sort of back off policy in case it keeps failing really quickly, 'cause it'll (1) peg the CPU, and (2) fill up the stack space.
You can avoid the latter by converting this into a tailrec:
@tailrec
def keepTrying[T](until: Deadline)(what: => T): T = try {
what
catch { case _ if until.hasTimeLeft =>
keepTrying(until)(what)
}
... but this will still spin the cpu a lot if your operation keeps failing quickly. Something like Thread.sleep(100)
before retrying might be wise.
Upvotes: 1