Created
May 20, 2011 15:32
-
-
Save realbot/983175 to your computer and use it in GitHub Desktop.
Retrying with style
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
val retryBlock = new Retry[String](6) | |
import retryBlock.retry | |
retry { | |
doSomething(somePar) | |
} giveup { | |
case e: Exception => handleException(e) | |
} |
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.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() } | |
} | |
} |
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 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