运维开发网

如何将基于时间的观察者添加到Scala Future?

运维开发网 https://www.qedev.com 2020-06-13 11:44 出处:网络 作者:运维开发网整理
我想在 Scala Futures中添加一个after(d:FiniteDuration)(callback:=> Unit)util,它可以让我这样做: val f = Future(someTask) f.after(30.seconds) { println("f has not completed in 30 seconds!") } f.after(60.seconds) {
我想在 Scala Futures中添加一个after(d:FiniteDuration)(callback:=> Unit)util,它可以让我这样做:

val f = Future(someTask)

f.after(30.seconds) {
  println("f has not completed in 30 seconds!")
}

f.after(60.seconds) {
  println("f has not completed in 60 seconds!")
}

我怎样才能做到这一点?

通常我使用线程池执行器并承诺:

import scala.concurrent.duration._
import java.util.concurrent.{Executors, ScheduledThreadPoolExecutor}
import scala.concurrent.{Future, Promise}

val f: Future[Int] = ???

val executor = new ScheduledThreadPoolExecutor(2, Executors.defaultThreadFactory(), AbortPolicy)

def withDelay[T](operation: ⇒ T)(by: FiniteDuration): Future[T] = {
  val promise = Promise[T]()
  executor.schedule(new Runnable {
    override def run() = {
      promise.complete(Try(operation))
    }
  }, by.length, by.unit)
  promise.future
}

Future.firstCompletedOf(Seq(f, withDelay(println("still going"))(30 seconds)))
Future.firstCompletedOf(Seq(f, withDelay(println("still still going"))(60 seconds)))
0

精彩评论

暂无评论...
验证码 换一张
取 消