Kotlin + Akka Part 4: Scheduling

Blockchain.com Engineering
Blockchain.com Engineering
2 min readMay 7, 2018

By now, you have played around with creating basic Actors and Actor hierarchies. It’s important to note that messages are delivered to Actors sequentially; this means no more than one dispatcher thread will ever call the Actor.

Akka provides a scheduler that will put a message in the target Actor’s mailbox at a specified point in the future. As one would expect, the API allows for scheduling a one-off task or a repeating task using context.system.scheduler.

You can schedule a Once Off Task, using context.system.scheduler.scheduleOnce(), and providing the delay, the target Actor, the dispatcher to use, the message to put in the target Actor’s mailbox, and the sender. As the API indicates, the message will be sent once to the target Actor after the delay has been reached.

You can schedule a Repeating Task that periodically sends a message to the target Actor in fixed time intervals. It is accessed using context.system.scheduler.schedule() for which you can additionally configure the initial interval and the repeating interval; the API call returns akka.actor.Cancellable which allows the repeating task to be cancelled. For example

An alternative way to schedule a repeating task is by rescheduling one-off tasks each time the task’s message is received by the Actor. In this method, you will move control over to the repeating task and, if the Actor is killed, the tasks are never rescheduled (ie. there are no akka.actor.Cancellable to manage). Another benefit is that the repeating interval is adjusted according to the time it takes to process the message.

The Akka scheduler is recommended for short term scheduled tasks that do not require high precision. If you need to schedule long term, consider using akka-quartz-scheduler which provides a quartz scheduler with Akka. This is a really useful extension and provides a variety of ways to setup your quartz configuration. For example:

In our next post, we will explore the Akka Event Stream.

--

--

Blockchain.com Engineering
Blockchain.com Engineering

The Blockchain.com engineering team is building an open, accessible, and fair financial future, one piece of software at a time. Learn more at blockchain.com