Akka Scheduler: Actors with Heartbeats

by
Tags: , ,
Category:

Akka is an excellent platform for writing concurrent applications using the Actor model. Chariot architect Anatoly Polinsky describes the Akka scheduler and how you can use it to create a heartbeat for an actor. From Anatoly’s blog:

AKKA Scheduler: Sending Message to Actor’s Self on Start

Akka has a little scheduler written using actors. This can be convenient if you want to schedule some periodic task for maintenance or similar. It allows you to register a message that you want to be sent to a specific actor at a periodic interval.

How Does AKKA Schedule Things?

Behind the scenes, AKKA scheduler relies on “ScheduledExecutorService” from the “java.util.concurrent” package. Hence when AKKA Scheduler needs to schedule “a message sent to an actor, given a certain initial delay and interval”, it just wraps the task of sending a message in a “java.lang.Runnable”, and uses a “ScheduledExecutorService” to schedule it:

***ISSUES****

service.
scheduleAtFixedRate
( createSendRunnable( receiver, message, true ),
initialDelay, delay, timeUnit).asInstanceOf[ScheduledFuture[AnyRef]]

“Heartbeat” Actor

Let’s look at the example of scheduling a message that should be sent to an Actor’s “self” as the Actor on start. Why? Because it is a cool use case : )

“Heartbeat” would be an ideal example of such use case => “When a ‘Hearbeat Actor’ starts, it should start sending heartbeats with a given interval (e.g. every 2 seconds)”

Creating a Message

First we need to create a message that will be scheduled to be sent every so often. We’ll call it a “SendHeartbeat” message:

*****ISSUES******

sealed trait HeartbeatMessage 
case
object SendHeartbeat extends HeartbeatMessage

Read the full post at: AKKA Scheduler: Sending Message to Actor’s Self on Start