Last active
July 23, 2023 23:48
-
-
Save viktorklang/9414163 to your computer and use it in GitHub Desktop.
Asynchronous retry for Future in Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.concurrent.duration._ | |
import scala.concurrent.ExecutionContext | |
import scala.concurrent.Future | |
import akka.pattern.after | |
import akka.actor.Scheduler | |
/** | |
* Given an operation that produces a T, returns a Future containing the result of T, unless an exception is thrown, | |
* in which case the operation will be retried after _delay_ time, if there are more possible retries, which is configured through | |
* the _retries_ parameter. If the operation does not succeed and there is no retries left, the resulting Future will contain the last failure. | |
**/ | |
def retry[T](op: => T, delay: FiniteDuration, retries: Int)(implicit ec: ExecutionContext, s: Scheduler): Future[T] = | |
Future(op) recoverWith { case _ if retries > 0 => after(delay, s)(retry(op, delay, retries - 1)) } |
Allow me to agree with Graingert that a license would be great to have.
May I suggest the Beerware license?
"BeerWare: If you have the time and money, send me a bottle of your favourite beer. If not, just send me a mail or something. Copy and use as you wish; just leave the author's name where you find it."
@nikolovivan - As @tadej-mali points out, the call-by-name parameter is evaluated each time it is referenced; it is not a thunk.
Note that the operation parameter (originally op, then f in the comments) should not have any side effects (e.g. logging), since they might be done several times. In some special situations this might not be a problem though.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Looking at example at https://docs.scala-lang.org/tour/by-name-parameters.html - isn't the by-name parameter evaluated each time when accessed? The
condition: => Boolean
would ne er evaluate tofalse
when it wastrue
initally. Or am I missing something?