krispo
krispo

Reputation: 526

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. How can simply do this?

Thanks!

Upvotes: 0

Views: 1110

Answers (2)

Mjonir74
Mjonir74

Reputation: 261

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.

Upvotes: 1

Carsten
Carsten

Reputation: 18446

Play integrates Akka for scheduling. In Play's documentation, you can find an example for running a block of code once with a set delay:

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. The argument (10.seconds) in the example is a FiniteDuration, so in your case, you'd probably want to set it to i seconds.

Upvotes: 1

Related Questions