如何在没有java.util.Timer的情况下实现延迟的将来? [英] How to implement a delayed future without java.util.Timer?
问题描述
我正在编写一个简单的函数来返回 Future [Unit]
,该延迟在给定的延迟后完成.
I am writing a simple function to return a Future[Unit]
that completes after a given delay.
def delayedFuture(delay: FiniteDuration): Future[Unit] = {
val promise = Promise[Unit]()
val timerTask = new java.util.TimerTask {
override def run(): Unit = promise.complete(Success(()))
}
new java.util.Timer().schedule(timerTask, delay.toMillis)
promise.future
}
此实现可能可以工作,但我不喜欢为每次调用创建新的 Timer
,因为每个 Timer
实例都会创建一个线程.我可以将 Timer
实例作为参数传递给 delayedFuture
,但我不希望客户端代码了解 Timer
.所以我想我根本不能使用 java.util.Timer
.
This implementation can probably work but I don't like creating a new Timer
for each invocation because each Timer
instance creates a thread. I can pass a Timer
instance to delayedFuture
as an argument but I don't want client code to know about Timer
. So I guess I cannot use java.util.Timer
at all.
我想使用 ExecutionContext
进行任务调度,并可能像这样定义 delayedFuture
:
I would like to use ExecutionContext
for task scheduling and maybe define delayedFuture
like this:
def delayedFuture(delay: FiniteDuration)
(implicit ec: ExecutoionContext): Future[Unit] = ???
在没有 java.util.Timer
的情况下实现这样的 delayedFuture
的最简单方法是什么?
What is the simplest way to implement delayedFuture
like this without java.util.Timer
?
推荐答案
您无需为每次调用创建新的 Timer
.只需创建一个全局的.
You don't need to create a new Timer
for each invocation. Just make one global one.
object Delayed {
private val timer = new Timer
def apply[T](delay: Duration)(task: => T): Future[T] = {
val promise = Promise[T]()
val tt = new TimerTask {
override def run(): Unit = promise.success(task)
}
timer.schedule(tt, delay.toMillis)
promise.future
}
def unit(delay: Duration) = apply[Unit](delay) { () }
}
然后, Delayed.unit(10秒)
为您提供一个可以在10秒内满足的未来单位.
Then, Delayed.unit(10 seconds)
gives you a future unit that satisfies in 10 seconds.
这篇关于如何在没有java.util.Timer的情况下实现延迟的将来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!