Scheduled Executor in Scala

I have been looking for a scala api for scheduled execution as well.

Java's ScheduledExecutor:

  • uses a thread pool for running the scheduler and operating the timeouts, and so does not require a Thread per timeout
  • No akka needed

I wrote a little scala wrapper for the single task scheduling. See the gist: https://gist.github.com/platy/8f0e634c64d9fb54559c


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.


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 { _ => }