【发布时间】:2021-07-06 04:39:15
【问题描述】:
假设我有一个函数fab: A => Future[B] 并希望它返回一个在截止日期之前完成的新未来。所以我正在写一个像这样的新函数deadlined
def deadlined[B](fut: => Future[B], deadline: Deadline): Future[B] = ???
现在我使用java.util.Timer,但可以使用ScheduledThreadPoolExecutor 作为suggested。最好的解决方案可能是一个包装器,用于抽象出调度实现并在测试中将其模拟为 cmets 中的suggested。
object Deadlined {
private val timer = new java.util.Timer() // todo: replace it with a wrapper
def apply[B](fut: => Future[B], deadline: Deadline)(implicit ec: ExecutionContext): Future[B] = {
val promise = Promise[B]()
val timerTask = new java.util.TimerTask {
override def run(): Unit = promise.failure(new Exception(s"$deadline is exceeded"))
}
timer.schedule(timerTask, deadline.timeLeft.toMillis)
fut.transform { result =>
timerTask.cancel()
result match {
case Success(b) => promise.success(b)
case Failure(t) => promise.failure(t)
}
result
}
promise.future
}
}
这有意义吗?我还想知道如何从对我上一个问题的回复中提取出Deadlined 和Delayed 的共同部分。
【问题讨论】:
-
Deadline是什么? -
像您已经完成的那样创建截止日期未来。然后使用
Future.firstCompletedOf。 -
取消定时任务怎么办?