Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
612 views
in Technique[技术] by (71.8m points)

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

I need to call into a service that may or not return timely results. I'd like to be able to write

val result = runWithTimeout(5000, valReturnedOnTimeout) { service.fetch }

Is there a standard function that will do the job - like Ruby's timeout?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...