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

后端 未结 6 462
伪装坚强ぢ
伪装坚强ぢ 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 02:57

    Something that hasn't been mentioned yet is awaitEither, a method on the actors package's Futures object. awaitEither returns the result from the first of a pair of futures to complete, so for example something like this could be used:

    awaitEither(future{task}, alarm(timeoutPeriod))
    

    and then dressed up in a method as suggested:

    def runWithTimeout[T](timeoutPeriod: Int, timeoutValue: T)(task: => T) = {
      awaitEither(future{task}, alarm(timeoutPeriod)) match {case () => timeoutValue case x => x}
    }
    

    alarm returns Unit which is assignable to a val of type Any so awaitEither returns something that can be pattern matched against.

提交回复
热议问题