Last active
March 18, 2021 18:58
-
-
Save ZviMints/060cd50501dd8edae5bd9b05799f0d90 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.{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