Skip to content

Instantly share code, notes, and snippets.

@JohnMurray
Last active January 27, 2018 21:57
Show Gist options
  • Save JohnMurray/28e918842df5c91ec7e14c7c68826ac6 to your computer and use it in GitHub Desktop.
Save JohnMurray/28e918842df5c91ec7e14c7c68826ac6 to your computer and use it in GitHub Desktop.
Simple retries with future-based networking code in Scala (with exponential back-off)
def networkRequestWithRetries(factor: Float = 1.5f, init: Int = 1, cur: Int = 0)
(implicit as: ActorSystem): Future[String] = {
networkRequest().recoverWith {
case NetworkException =>
val next: Int =
if (cur == 0) init
else Math.ceil(cur * factor).toInt
println(s"retrying after ${next} ms")
after(next.milliseconds, as.scheduler, global, Future.successful(1)).flatMap { _ =>
networkRequestWithRetries(factor, init, next)
}
case t: Throwable => throw t
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment