Scala - ScheduledFuture

前端 未结 7 1127
感动是毒
感动是毒 2020-12-08 04:27

I am trying to implement scheduled future in Scala. I would like it to wait specific time and then execute the body. So far I tried the following, simple approach

         


        
7条回答
  •  忘掉有多难
    2020-12-08 05:03

    My solution is pretty similar to Régis's but I use Akka to schedule:

     def delayedFuture[T](delay: FiniteDuration)(block: => T)(implicit executor : ExecutionContext): Future[T] = {
        val promise = Promise[T]
    
        Akka.system.scheduler.scheduleOnce(delay) {
          try {
            val result = block
            promise.complete(Success(result))
          } catch {
            case t: Throwable => promise.failure(t)
          }
        }
        promise.future
      }
    

提交回复
热议问题