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

后端 未结 6 463
伪装坚强ぢ
伪装坚强ぢ 2020-12-19 02:40

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) {         


        
6条回答
  •  眼角桃花
    2020-12-19 03:05

    You could use a future

    import scala.actors.Futures._  
    
    val myfuture = 
        future {
         Thread.sleep(5000)
         println("")
         "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!!!")
        }
      }
    }
    

提交回复
热议问题