Skip to content

Instantly share code, notes, and snippets.

@yashap
Created September 25, 2015 18:49
Show Gist options
  • Save yashap/150f19199603469b1149 to your computer and use it in GitHub Desktop.
Save yashap/150f19199603469b1149 to your computer and use it in GitHub Desktop.
Retry a future on failure, with a delay, up to n times
import scala.concurrent.{Promise, Future, ExecutionContext}
import scala.concurrent.duration.FiniteDuration
import java.util.{TimerTask, Timer}
// Inspired by https://gist.github.com/viktorklang/9414163, but modified to not depend on Akka, works with just Scala's standard library
def retry[T](block: => T, delay: FiniteDuration, retries: Int)(implicit ec: ExecutionContext): Future[T] =
Future(block).recoverWith { case _ if retries > 0 =>
after(delay)(retry(block, delay, retries - 1))
}
def after[T](delay: FiniteDuration)(block: => Future[T])(implicit ec: ExecutionContext): Future[T] = {
val promise = Promise[T]()
new Timer().schedule(
new TimerTask {
override def run(): Unit =
block.onComplete { case x => promise.complete(x) }
},
delay.toMillis
)
promise.future
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment