Scheduling Messages in Akka

Reading Time: 2 minutes

Take a situation where you want to make an actor sleep and it should resume after a period of time. Or you want your actor to perform a task on a recurring basis then you must schedule a message. Here I will discuss how to do that !!

Scheduled delivery of messages

  • Often, a need exists to schedule the sending of a message to an actor:
    • a single time after some delay (send a message for once after a period of time and then we never send that message)
    • periodically with a given interval (e.g after every 5sec, 5min, etc.)
  • Two Akka facilities exist to achieve this:
    • The Akka Scheduler service
    • The akka.actors.Timers trait
  • Let’s discuss both of them one by one !!

Scheduler Service

import context.dispatcher
import scala.concurrent.duration._

2 seconds,      // provide the delay
self,          //actor name on which we want a scheduling message 
ShradhaSaxena  //message that you want to deliver
  • A scheduler is something that is provided by the actor system:
    • Allows to run a task or send a message to an actor
    • Scheduling could be once or on a periodic basis
  • You need an implicit ExecutionContext, e.g. an actor’s dispatcher

Timers Trait

import scala.concurrent.duration._

class AkkaLearner(..<elided>..) extends Actor with ActorLogging with Timers {
"Let's start learning akka",      // Name for the timer
ShradhaSaxena,        // Message to be passed
2 seconds             // delay
  • As of AKKA 2.5, to schedule the sending of a message to self after a given time:
    • Mix-in the trait which will give you access to the timers field
    • Use methods timers.startSingleTimer (for sending message once) or timers.startPeriodicTimer to schedule events periodically
    • Name a timer by passing in a key (type Any)

Scheduler Service versus Timers

  • Timers are bond to the lifecycle of the actor that owns it and thus are canceled automatically when the actor is restarted or stopped. As a consequence the risk is eliminated from having:
    • zombie‘ timer events in case of stopping an actor. As the timer will also die when the actor has died
    • If we restart an actor then the timer may also get restarted and hence cause doubling of events
  • Timer guarantees that a message from a canceled timer, will not be received by the actor, even though the message might already be enqueued in the mailbox when cancel is called
  • The Scheduler Service supports sending timed events to other actors

“KEY POINT” –> When scheduling periodic or single messages in an actor to itself, use the Actor Timers instead of the Scheduler directly.

I hope the blog is beneficial for you.