Scheduler
Loading

Scheduler

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.

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 job buckets which are emptied according to a fixed schedule. It does not execute tasks at the exact time, but on every tick, it will run everything that is (over)due. The accuracy of the default Scheduler can be modified by the akka.scheduler.tick-duration configuration property.

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 a message to the testActor) after 50ms
  2. system.scheduler.scheduleOnce(50 milliseconds) {
  3. testActor ! System.currentTimeMillis
  4. }
  1. val Tick = "tick"
  2. class TickActor extends Actor {
  3. def receive = {
  4. case Tick //Do something
  5. }
  6. }
  7. val tickActor = system.actorOf(Props(classOf[TickActor], this))
  8. //Use system's dispatcher as ExecutionContext
  9. import system.dispatcher
  10.  
  11. //This will schedule to send the Tick-message
  12. //to the tickActor after 0ms repeating every 50ms
  13. val cancellable =
  14. system.scheduler.schedule(0 milliseconds,
  15. 50 milliseconds,
  16. tickActor,
  17. Tick)
  18.  
  19. //This cancels further Ticks to be sent
  20. cancellable.cancel()

Warning

If you schedule functions or Runnable instances you should be extra careful to not close over unstable references. In practice this means not using this inside the closure in the scope of an Actor instance, not accessing sender directly and not calling the methods of the Actor instance directly. If you need to schedule an invocation schedule a message to self instead (containing the necessary parameters) and then call the method when the message is received.

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

The actual scheduler implementation is loaded reflectively upon ActorSystem start-up, which means that it is possible to provide a different one using the akka.scheduler.implementation configuration property. The referenced class must implement the following 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. * Scheduler implementation are loaded reflectively at ActorSystem start-up
  11. * with the following constructor arguments:
  12. * 1) the system’s com.typesafe.config.Config (from system.settings.config)
  13. * 2) a akka.event.LoggingAdapter
  14. * 3) a java.util.concurrent.ThreadFactory
  15. */
  16. trait Scheduler {
  17. /**
  18. * Schedules a message to be sent repeatedly with an initial delay and
  19. * frequency. E.g. if you would like a message to be sent immediately and
  20. * thereafter every 500ms you would set delay=Duration.Zero and
  21. * interval=Duration(500, TimeUnit.MILLISECONDS)
  22. *
  23. * Java & Scala API
  24. */
  25. final def schedule(
  26. initialDelay: FiniteDuration,
  27. interval: FiniteDuration,
  28. receiver: ActorRef,
  29. message: Any)(implicit executor: ExecutionContext,
  30. sender: ActorRef = Actor.noSender): Cancellable =
  31. schedule(initialDelay, interval, new Runnable {
  32. def run = {
  33. receiver ! message
  34. if (receiver.isTerminated)
  35. throw new SchedulerException("timer active for terminated actor")
  36. }
  37. })
  38.  
  39. /**
  40. * Schedules a function to be run repeatedly with an initial delay and a
  41. * frequency. E.g. if you would like the function to be run after 2 seconds
  42. * and thereafter every 100ms you would set delay = Duration(2, TimeUnit.SECONDS)
  43. * and interval = Duration(100, TimeUnit.MILLISECONDS)
  44. *
  45. * Scala API
  46. */
  47. final def schedule(
  48. initialDelay: FiniteDuration,
  49. interval: FiniteDuration)(f: Unit)(
  50. implicit executor: ExecutionContext): Cancellable =
  51. schedule(initialDelay, interval, new Runnable { override def run = f })
  52.  
  53. /**
  54. * Schedules a function to be run repeatedly with an initial delay and
  55. * a frequency. E.g. if you would like the function to be run after 2
  56. * seconds and thereafter every 100ms you would set delay = Duration(2,
  57. * TimeUnit.SECONDS) and interval = Duration(100, TimeUnit.MILLISECONDS)
  58. *
  59. * Java API
  60. */
  61. def schedule(
  62. initialDelay: FiniteDuration,
  63. interval: FiniteDuration,
  64. runnable: Runnable)(implicit executor: ExecutionContext): Cancellable
  65.  
  66. /**
  67. * Schedules a message to be sent once with a delay, i.e. a time period that has
  68. * to pass before the message is sent.
  69. *
  70. * Java & Scala API
  71. */
  72. final def scheduleOnce(
  73. delay: FiniteDuration,
  74. receiver: ActorRef,
  75. message: Any)(implicit executor: ExecutionContext,
  76. sender: ActorRef = Actor.noSender): Cancellable =
  77. scheduleOnce(delay, new Runnable {
  78. override def run = receiver ! message
  79. })
  80.  
  81. /**
  82. * Schedules a function to be run once with a delay, i.e. a time period that has
  83. * to pass before the function is run.
  84. *
  85. * Scala API
  86. */
  87. final def scheduleOnce(delay: FiniteDuration)(f: Unit)(
  88. implicit executor: ExecutionContext): Cancellable =
  89. scheduleOnce(delay, new Runnable { override def run = f })
  90.  
  91. /**
  92. * Schedules a Runnable to be run once with a delay, i.e. a time period that
  93. * has to pass before the runnable is executed.
  94. *
  95. * Java & Scala API
  96. */
  97. def scheduleOnce(
  98. delay: FiniteDuration,
  99. runnable: Runnable)(implicit executor: ExecutionContext): Cancellable
  100.  
  101. /**
  102. * The maximum supported task frequency of this scheduler, i.e. the inverse
  103. * of the minimum time interval between executions of a recurring task, in Hz.
  104. */
  105. def maxFrequency: Double
  106.  
  107. }

The Cancellable interface

Scheduling a task will result in a Cancellable (or throw an IllegalStateException if attempted after the scheduler’s shutdown). 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. Check the return value of cancel to detect whether the scheduled task was canceled or will (eventually) have run.

  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 and returns true if that was successful.
  9. * If this cancellable was (concurrently) cancelled already, then this method
  10. * will return false although isCancelled will return true.
  11. *
  12. * Java & Scala API
  13. */
  14. def cancel(): Boolean
  15.  
  16. /**
  17. * Returns true if and only if this Cancellable has been successfully cancelled
  18. *
  19. * Java & Scala API
  20. */
  21. def isCancelled: Boolean
  22. }