Skip to content

Instantly share code, notes, and snippets.

@ZviMints
Last active March 18, 2021 18:58
Show Gist options
  • Save ZviMints/060cd50501dd8edae5bd9b05799f0d90 to your computer and use it in GitHub Desktop.
Save ZviMints/060cd50501dd8edae5bd9b05799f0d90 to your computer and use it in GitHub Desktop.
Asynchronous retry for Future in Scala
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
import scala.concurrent.duration.FiniteDuration
import scala.util.control.NonFatal
import scala.concurrent.ExecutionContext.Implicits.global
def foo(): Future[Unit] = if(Math.random() >= 1/3) Future.failed(new RuntimeException("")) else Future.successful(())
def retry[T](retries: Int, delay: FiniteDuration)(fn: => Future[T]): Future[T] = {
fn recoverWith {
case NonFatal(_) if retries > 0 =>
println(s"Retry($retries) failed")
Thread.sleep(delay.toMillis)
retry(retries - 1, delay)(fn)
case ex => Future.failed(ex)
}
}
Await.result(
retry(3, 1.seconds) {
foo()
}, Duration.Inf)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment