Scheduler (Scala)
Loading

Scheduler (Scala)

Sometimes the need for making things happen in the future arises, and where do you go look then? Look no further than ActorSystem! There you find the scheduler method that returns an instance of akka.actor.Scheduler, this instance is unique per ActorSystem and is used internally for scheduling things to happen at specific points in time. Please note that the scheduled tasks are executed by the default MessageDispatcher of the ActorSystem.

You can schedule sending of messages to actors and execution of tasks (functions or Runnable). You will get a Cancellable back that you can call cancel on to cancel the execution of the scheduled operation.

Warning

The default implementation of Scheduler used by Akka is based on the Netty HashedWheelTimer. It does not execute tasks at the exact time, but on every tick, it will run everything that is overdue. The accuracy of the default Scheduler can be modified by the "ticks-per-wheel" and "tick-duration" configuration properties. For more information, see: HashedWheelTimers.

Some examples

  1. import akka.actor.Actor
  2. import akka.actor.Props
  3. import scala.concurrent.duration._
  4.  
  5. //Use the system's dispatcher as ExecutionContext
  6. import system.dispatcher
  7.  
  8. //Schedules to send the "foo"-message to the testActor after 50ms
  9. system.scheduler.scheduleOnce(50 milliseconds, testActor, "foo")
  1. //Schedules a function to be executed (send the current time) to the testActor after 50ms
  2. system.scheduler.scheduleOnce(50 milliseconds) {
  3. testActor ! System.currentTimeMillis
  4. }
  1. val Tick = "tick"
  2. val tickActor = system.actorOf(Props(new Actor {
  3. def receive = {
  4. case Tick //Do something
  5. }
  6. }))
  7. //Use system's dispatcher as ExecutionContext
  8. import system.dispatcher
  9.  
  10. //This will schedule to send the Tick-message
  11. //to the tickActor after 0ms repeating every 50ms
  12. val cancellable =
  13. system.scheduler.schedule(0 milliseconds,
  14. 50 milliseconds,
  15. tickActor,
  16. Tick)
  17.  
  18. //This cancels further Ticks to be sent
  19. cancellable.cancel()

From akka.actor.ActorSystem

  1. /**
  2. * Light-weight scheduler for running asynchronous tasks after some deadline
  3. * in the future. Not terribly precise but cheap.
  4. */
  5. def scheduler: Scheduler

The Scheduler interface

  1. /**
  2. * An Akka scheduler service. This one needs one special behavior: if
  3. * Closeable, it MUST execute all outstanding tasks upon .close() in order
  4. * to properly shutdown all dispatchers.
  5. *
  6. * Furthermore, this timer service MUST throw IllegalStateException if it
  7. * cannot schedule a task. Once scheduled, the task MUST be executed. If
  8. * executed upon close(), the task may execute before its timeout.
  9. */
  10. trait Scheduler {
  11. /**
  12. * Schedules a message to be sent repeatedly with an initial delay and
  13. * frequency. E.g. if you would like a message to be sent immediately and
  14. * thereafter every 500ms you would set delay=Duration.Zero and
  15. * interval=Duration(500, TimeUnit.MILLISECONDS)
  16. *
  17. * Java & Scala API
  18. */
  19. def schedule(
  20. initialDelay: FiniteDuration,
  21. interval: FiniteDuration,
  22. receiver: ActorRef,
  23. message: Any)(implicit executor: ExecutionContext): Cancellable
  24.  
  25. /**
  26. * Schedules a function to be run repeatedly with an initial delay and a
  27. * frequency. E.g. if you would like the function to be run after 2 seconds
  28. * and thereafter every 100ms you would set delay = Duration(2, TimeUnit.SECONDS)
  29. * and interval = Duration(100, TimeUnit.MILLISECONDS)
  30. *
  31. * Scala API
  32. */
  33. def schedule(
  34. initialDelay: FiniteDuration,
  35. interval: FiniteDuration)(f: Unit)(
  36. implicit executor: ExecutionContext): Cancellable
  37.  
  38. /**
  39. * Schedules a function to be run repeatedly with an initial delay and
  40. * a frequency. E.g. if you would like the function to be run after 2
  41. * seconds and thereafter every 100ms you would set delay = Duration(2,
  42. * TimeUnit.SECONDS) and interval = Duration(100, TimeUnit.MILLISECONDS)
  43. *
  44. * Java API
  45. */
  46. def schedule(
  47. initialDelay: FiniteDuration,
  48. interval: FiniteDuration,
  49. runnable: Runnable)(implicit executor: ExecutionContext): Cancellable
  50.  
  51. /**
  52. * Schedules a Runnable to be run once with a delay, i.e. a time period that
  53. * has to pass before the runnable is executed.
  54. *
  55. * Java & Scala API
  56. */
  57. def scheduleOnce(
  58. delay: FiniteDuration,
  59. runnable: Runnable)(implicit executor: ExecutionContext): Cancellable
  60.  
  61. /**
  62. * Schedules a message to be sent once with a delay, i.e. a time period that has
  63. * to pass before the message is sent.
  64. *
  65. * Java & Scala API
  66. */
  67. def scheduleOnce(
  68. delay: FiniteDuration,
  69. receiver: ActorRef,
  70. message: Any)(implicit executor: ExecutionContext): Cancellable
  71.  
  72. /**
  73. * Schedules a function to be run once with a delay, i.e. a time period that has
  74. * to pass before the function is run.
  75. *
  76. * Scala API
  77. */
  78. def scheduleOnce(
  79. delay: FiniteDuration)(f: Unit)(
  80. implicit executor: ExecutionContext): Cancellable
  81. }

The Cancellable interface

This allows you to cancel something that has been scheduled for execution.

Warning

This does not abort the execution of the task, if it had already been started.

  1. /**
  2. * Signifies something that can be cancelled
  3. * There is no strict guarantee that the implementation is thread-safe,
  4. * but it should be good practice to make it so.
  5. */
  6. trait Cancellable {
  7. /**
  8. * Cancels this Cancellable
  9. *
  10. * Java & Scala API
  11. */
  12. def cancel(): Unit
  13.  
  14. /**
  15. * Returns whether this Cancellable has been cancelled
  16. *
  17. * Java & Scala API
  18. */
  19. def isCancelled: Boolean
  20. }