In Java I can use Scheduled Executor to schedule tasks to run after a given delay. I can use it in Scala but I wonder if there is a Scala API for that.
Is there any Scala API (as opposed to Scheduled Executor in Java) to schedule tasks?
In Java I can use Scheduled Executor to schedule tasks to run after a given delay. I can use it in Scala but I wonder if there is a Scala API for that.
Is there any Scala API (as opposed to Scheduled Executor in Java) to schedule tasks?
Akka has something similar with schedulers:
http://doc.akka.io/api/akka/2.1.4/#akka.actor.Scheduler
You can obtain one from the actor system:
val actorSystem = ActorSystem()
val scheduler = actorSystem.scheduler
val task = new Runnable { def run() { log.info("Hello") } }
implicit val executor = actorSystem.dispatcher
scheduler.schedule(
initialDelay = Duration(5, TimeUnit.SECONDS),
interval = Duration(10, TimeUnit.SECONDS),
runnable = task)
If you are using Akka or something based on it, like Play, that would be the way to go.
I have been looking for a scala api for scheduled execution as well.
Java's ScheduledExecutor:
I wrote a little scala wrapper for the single task scheduling. See the gist: https://gist.github.com/platy/8f0e634c64d9fb54559c
You can use scalaz's Task,
import scala.concurrent.duration.{FiniteDuration, SECONDS}
import scalaz.concurrent.Task
Task.schedule(Console.println("time's up"), FiniteDuration(5, SECONDS)).runAsync { _ => }
As an alternative, there is Monix scheduler too: https://monix.io/docs/3x/execution/scheduler.html
It use a Java's Scheduled Executor behind, but it is wrapped and transparent.
You need to implement some Runnable to be executed, which is lighter than Akka Actor.
For example, you can do (taken from the documentation):
lazy val scheduler =
Scheduler.singleThread(name="my-thread")
// First execution in 3 seconds, then every 5 seconds
val c = scheduler.scheduleAtFixedRate(
3, 5, TimeUnit.SECONDS,
new Runnable {
def run(): Unit = {
println("Fixed delay task")
}
})
// If we change our mind and want to cancel
c.cancel()