Scheduler - Version 2.4.20

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(
  15. 0 milliseconds,
  16. 50 milliseconds,
  17. tickActor,
  18. Tick)
  19.  
  20. //This cancels further Ticks to be sent
  21. 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

Warning

All scheduled task will be executed when the ActorSystem is terminated, i.e. the task may execute before its timeout.

§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
  30. executor: ExecutionContext,
  31. sender: ActorRef = Actor.noSender): Cancellable =
  32. schedule(initialDelay, interval, new Runnable {
  33. def run = {
  34. receiver ! message
  35. if (receiver.isTerminated)
  36. throw new SchedulerException("timer active for terminated actor")
  37. }
  38. })
  39.  
  40. /**
  41. * Schedules a function to be run repeatedly with an initial delay and a
  42. * frequency. E.g. if you would like the function to be run after 2 seconds
  43. * and thereafter every 100ms you would set delay = Duration(2, TimeUnit.SECONDS)
  44. * and interval = Duration(100, TimeUnit.MILLISECONDS). If the execution of
  45. * the function takes longer than the interval, the subsequent execution will
  46. * start immediately after the prior one completes (there will be no overlap
  47. * of the function executions). In such cases, the actual execution interval
  48. * will differ from the interval passed to this method.
  49. *
  50. * If the function throws an exception the repeated scheduling is aborted,
  51. * i.e. the function will not be invoked any more.
  52. *
  53. * Scala API
  54. */
  55. final def schedule(
  56. initialDelay: FiniteDuration,
  57. interval: FiniteDuration)(f: Unit)(
  58. implicit
  59. executor: ExecutionContext): Cancellable =
  60. schedule(initialDelay, interval, new Runnable { override def run = f })
  61.  
  62. /**
  63. * Schedules a `Runnable` to be run repeatedly with an initial delay and
  64. * a frequency. E.g. if you would like the function to be run after 2
  65. * seconds and thereafter every 100ms you would set delay = Duration(2,
  66. * TimeUnit.SECONDS) and interval = Duration(100, TimeUnit.MILLISECONDS). If
  67. * the execution of the runnable takes longer than the interval, the
  68. * subsequent execution will start immediately after the prior one completes
  69. * (there will be no overlap of executions of the runnable). In such cases,
  70. * the actual execution interval will differ from the interval passed to this
  71. * method.
  72. *
  73. * If the `Runnable` throws an exception the repeated scheduling is aborted,
  74. * i.e. the function will not be invoked any more.
  75. *
  76. * Java API
  77. */
  78. def schedule(
  79. initialDelay: FiniteDuration,
  80. interval: FiniteDuration,
  81. runnable: Runnable)(implicit executor: ExecutionContext): Cancellable
  82.  
  83. /**
  84. * Schedules a message to be sent once with a delay, i.e. a time period that has
  85. * to pass before the message is sent.
  86. *
  87. * Java & Scala API
  88. */
  89. final def scheduleOnce(
  90. delay: FiniteDuration,
  91. receiver: ActorRef,
  92. message: Any)(implicit
  93. executor: ExecutionContext,
  94. sender: ActorRef = Actor.noSender): Cancellable =
  95. scheduleOnce(delay, new Runnable {
  96. override def run = receiver ! message
  97. })
  98.  
  99. /**
  100. * Schedules a function to be run once with a delay, i.e. a time period that has
  101. * to pass before the function is run.
  102. *
  103. * Scala API
  104. */
  105. final def scheduleOnce(delay: FiniteDuration)(f: Unit)(
  106. implicit
  107. executor: ExecutionContext): Cancellable =
  108. scheduleOnce(delay, new Runnable { override def run = f })
  109.  
  110. /**
  111. * Schedules a Runnable to be run once with a delay, i.e. a time period that
  112. * has to pass before the runnable is executed.
  113. *
  114. * Java & Scala API
  115. */
  116. def scheduleOnce(
  117. delay: FiniteDuration,
  118. runnable: Runnable)(implicit executor: ExecutionContext): Cancellable
  119.  
  120. /**
  121. * The maximum supported task frequency of this scheduler, i.e. the inverse
  122. * of the minimum time interval between executions of a recurring task, in Hz.
  123. */
  124. def maxFrequency: Double
  125.  
  126. }

§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. }