I am trying to implement scheduled future in Scala. I would like it to wait specific time and then execute the body. So far I tried the following, simple approach
val d = 5.seconds.fromNow
val f = future {Await.ready(Promise().future, d.timeLeft); 1}
val res = Await.result(f, Duration.Inf)
but I am getting the TimeoutExcpetion on the future. Is this even the correct approach or should I simply use the ScheduledExecutor from Java?
Shortest solution for this, is probably making use of scala-async:
Or in case you want delayed execution of a block
There is nothing to do that out of the box using the standard library alone. For most simple use cases, you can use a little helper such as this:
This can be used like this:
Note that unlike java scheduled futures, this implementation will not let you cancel the future.
Akka has akka.pattern:
"Returns a scala.concurrent.Future that will be completed with the success or failure of the provided value after the specified duration."
http://doc.akka.io/api/akka/2.2.1/#akka.pattern.package
My solution is pretty similar to Régis's but I use Akka to schedule:
All the other solutions use either akka or block a thread per delayed task. A better solution (unless you are already using akka) is to use java's ScheduledThreadPoolExecutor. Here's an example of a scala wrapper for that:
https://gist.github.com/platy/8f0e634c64d9fb54559c
You could change your code to something like this:
But I would not recommend it. In doing so, you would be blocking in a Future (blocking to wait for that
Promise
that will never complete), and I think blocking in theExecutionContext
is greatly discouraged. I would either look into using the java scheduled executor as you stated or you could look into using Akka as @alex23 recommended.