Is there a standard Scala function for running a block with a timeout?

With credit to the other answers - in the absence of any standard library function, I've gone down the Futures route.

  import scala.concurrent.ExecutionContext.Implicits.global
  import scala.concurrent._
  import scala.concurrent.duration._

  def runWithTimeout[T](timeoutMs: Long)(f: => T) : Option[T] = {
    Some(Await.result(Future(f), timeoutMs milliseconds))
  }

  def runWithTimeout[T](timeoutMs: Long, default: T)(f: => T) : T = {
    runWithTimeout(timeoutMs)(f).getOrElse(default)
  }

So that

  @Test def test {
    runWithTimeout(50) { "result" } should equal (Some("result"))
    runWithTimeout(50) { Thread.sleep(100); "result" } should equal (None)
    runWithTimeout(50, "no result") { "result" } should equal ("result")
    runWithTimeout(50, "no result") { Thread.sleep(100); "result" } should equal("no result")
  }

I'd be grateful for any feedback as to whether this is a good Scala style!


Might Futures and its alarm do the trick?


You could use a future

import scala.actors.Futures._  

val myfuture = 
    future {
     Thread.sleep(5000)
     println("<future>")
     "future "
 }

 awaitAll(300,myfuture ) foreach println _   

But also have a look at Circuit Breaker for Scala which is a implementation of the Circuit Breaker Pattern. Basically it lets you control the timeout and what should happen if a failure occurs accessing an external resource

Usage looks like this in Scala (from the readme) :

. . .
addCircuitBreaker("test", CircuitBreakerConfiguration(timeout=100,failureThreshold=10))
. . .


class Test extends UsingCircuitBreaker {
  def myMethodWorkingFine = {
    withCircuitBreaker("test") {
      . . .
    }
  }

  def myMethodDoingWrong = {
    withCircuitBreaker("test") {
      require(false,"FUBAR!!!")
    }
  }
}