是否有一个标准的Scala函数用于运行一个超时的块? [英] Is there a standard Scala function for running a block with a timeout?
本文介绍了是否有一个标准的Scala函数用于运行一个超时的块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要调用一个可能或不会及时返回结果的服务。我想能够写
val result = runWithTimeout(5000,valReturnedOnTimeout){service.fetch}
是否有一个标准函数可以完成这项工作 - 像Ruby的 timeout ?
解决方案
与其他答案 - 在没有任何标准库功能,我已经走了Futures路线。
def runWithTimeout [T](timeoutMs:Long)(f:=> T):Option [T] = {
awaitAll(timeoutMs,future(f))。head.asInstanceOf [Option [T]]
}
def runWithTimeout [T](timeoutMs:Long,default:T) f:=> T):T = {
runWithTimeout(timeoutMs)(f).getOrElse(default)
}
这样
@Test def test {
runWithTimeout(50) {result}应该等于(Some(result))
runWithTimeout(50){Thread.sleep(100); result} should be(None)
runWithTimeout(50,no result){result}应该等于(result)
runWithTimeout(50,no result睡眠(100); result}应该等于(无结果)
}
感谢任何关于这是否是一个好的Scala风格的反馈!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?
解决方案With credit to the other answers - in the absence of any standard library function, I've gone down the Futures route.
def runWithTimeout[T](timeoutMs: Long)(f: => T) : Option[T] = { awaitAll(timeoutMs, future(f)).head.asInstanceOf[Option[T]] } 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!
这篇关于是否有一个标准的Scala函数用于运行一个超时的块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文