0

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!

krispo
  • 526
  • 1
  • 4
  • 11
  • The code actually won't start all of them at the same time. It will schedule them. It is then up to the `ExecutionContext` to decide when they should actually run. So maybe you need a custom `ExecutionContext` instead. – James Ward Apr 15 '13 at 12:28
  • Sorry, I have no idea how to configure a custom `ExecutionContext`. – krispo Apr 15 '13 at 13:01
  • This link should get you on the right path for configuring a custom ExecutionContext: http://www.playframework.com/documentation/2.1.1/ThreadPools – Mjonir74 Jun 24 '13 at 20:47

2 Answers2

1

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.

Carsten
  • 17,991
  • 4
  • 48
  • 53
1

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.

Mjonir74
  • 261
  • 3
  • 9