[英]Time delay between futures in Play framework 2.1
I have a number of consuming works that are fully asynchronous and started roughly at the same time. 我有许多完全异步的消费作品,大致同时开始。 I mean something like this:
我的意思是这样的:
for (i <- 1 to n) {
Future { startWork("work" + i) }
}
But I need to add some time lag to start these works successively at the different time. 但是我需要增加一些时间延迟来在不同的时间连续开始这些工作。 For example, if (time lag = 1 second) => i-work starts after i seconds.
例如,如果(时间延迟= 1秒)=> i-work在i秒后开始。 How can simply do this?
怎么可以这么做?
Thanks! 谢谢!
Play integrates Akka for scheduling. Play集成Akka进行调度。 In Play's documentation , you can find an example for running a block of code once with a set delay:
在Play的文档中 ,您可以找到一个使用设置延迟运行一次代码块的示例:
import play.api.libs.concurrent.Execution.Implicits._
Akka.system.scheduler.scheduleOnce(10.seconds) {
file.delete()
}
Akka's documentation has some more info on its scheduler. Akka的文档中有关于其调度程序的更多信息。 The argument (
10.seconds
) in the example is a FiniteDuration
, so in your case, you'd probably want to set it to i seconds
. 示例中的参数(
10.seconds
)是一个FiniteDuration
,因此在您的情况下,您可能希望将其设置为i seconds
。
Yo Dawg! 哟道格! I heard you like Futures, so I'm going to show you how to execute a Future in the future so you can compose other Futures from your Future in the future.
我听说你喜欢期货,所以我将向你展示如何在未来执行未来,这样你就可以在未来从未来创造其他期货。
import play.api.concurrent.Akka
import scala.concurrent._
import scala.concurrent.duration._
val promise = Promise[Unit]
Akka.system.scheduler.scheduleOnce(1.seconds) { promise.success() }
promise.future.map { _ => /* The body of the Future to be run in the future */ }
This should be a non-blocking solution do delay the execution of a Future until some time in the future. 这应该是一个非阻塞解决方案,可以延迟Future的执行,直到将来的某个时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.