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

标签 scala scala-2.11 scala-2.12

我想添加一个 after(d: FiniteDuration)(callback: => Unit)使用 Scala Future s 这将使我能够做到这一点:

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!")
}

我怎样才能做到这一点?

最佳答案

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

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

关于scala - 如何将基于时间的观察者添加到 Scala Future?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37737092/

相关文章:

scala - 如何使用 Play Framework (scala)在HTML中打印@符号

scala - Scala 2.12 中的隐式 ExecutionContext 优先级

带下划线的 Scala 字符串插值

scala - scala 2.11 中弃用的 `scala.collection.script` 的替代方案?

字节的 Scala 十六进制文字

Scala 为特定测试设置配置值

scala - Scala 列表中的混合类型

json - 如何解决此Scala/Play编译错误(返回错误的类型)?

scala - Scala 的常规赋值与提取器赋值不平衡的原因是什么?