Skip to content

Instantly share code, notes, and snippets.

@realbot
Created May 20, 2011 15:32
Show Gist options
  • Save realbot/983175 to your computer and use it in GitHub Desktop.
Save realbot/983175 to your computer and use it in GitHub Desktop.
Retrying with style
val retryBlock = new Retry[String](6)
import retryBlock.retry
retry {
doSomething(somePar)
} giveup {
case e: Exception => handleException(e)
}
import scala.math._
import scala.util.control.Exception._
class Retry[T](maxRetry: Int) {
private var retryCount = 0
private var block: () => T = _
def retry(op: => T): Retry[T] = {
block = () => {
try {
op
} catch {
case t: Throwable =>
retryCount += 1
if (retryCount == maxRetry) {
throw t
} else {
val interval = round(pow(2, retryCount)) * 100;
Thread.sleep(interval)
block()
}
}
}
this
}
def giveup(handler: => Catcher[T]): T = {
catching(handler) { block() }
}
}
import org.specs2.mutable._
class TestRetry extends Specification {
"retry" should {
"retry six times" in {
val retryTimes = 6
val r = new Retry[String](retryTimes)
import r.retry
var count = 0
val start = System.currentTimeMillis
var result =
retry {
count += 1
throw new Exception("expected_exception")
} giveup {
case e: Exception => "OK"
}
(System.currentTimeMillis - start) must be_>=(6200L)
count must_== retryTimes
result must beEqualTo("OK")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment