How to Schedule Messages or Tasks in Akka?

Reading Time: 2 minutes

In this blog, we’ll see how to schedule sending of messages to actors or execution of tasks(functions or Runnable) at a specific point of time in future or maybe repeatedly over a certain interval. For this purpose, the Akka ActorSystem provides Akka Scheduler to manage the periodic execution of tasks.

Akka Scheduler

In simple words, the Akka Scheduler helps us to schedule sending of messages to actors or execution of tasks in the future(once or repeatedly).

When scheduling periodic or single messages in an actor to itself it is recommended to use the Actor Timers instead of using the Scheduler directly.

The Akka scheduler is not designed for long-term scheduling nor is it to be used for highly precise firing of the events. The maximum amount of time into the future you can schedule an event to trigger is around 8 months, which in practice is too much to be useful since this would assume the system never went down during that period. If you need long-term scheduling we highly recommend looking into alternative schedulers, as this is not the use-case the Akka scheduler is implemented for.

How to use it?

The Akka ActorSystem provides a 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.

Let’s see how we can us it to schedule messages by using an example.

We’ll begin with creating a simple Akka Actor that will log the message on receiving it.

class SimpleAkkaActor extends Actor with ActorLogging {
  override def receive: Receive = {
    case message => log.info(message.toString)
  }
}

Schedule Once

To schedule sending of a message to an actor or execution of task once after a certain delay. We’ll use the scheduleOnce method provided by the Scheduler. Here’s an example:

import akka.actor.{Actor, ActorLogging, ActorSystem, Cancellable, Props}
import scala.concurrent.duration.DurationInt

object ScheduleOnceExample extends App {
  val system = ActorSystem("AkkaSchedulerExample")
  val simpleActor = system.actorOf(Props[SimpleActor])

  //Use the system's dispatcher as ExecutionContext
  import system.dispatcher

  //Schedules to send the "Hello" message to the simpleActor after 500ms
  system.scheduler.scheduleOnce(500 milliseconds, simpleActor, "Hello")

  //Schedule a function, that sends the current time to the simpleActor,
  // to be executed after 1 second
  system.scheduler.scheduleOnce(1 second) {
    simpleActor ! System.currentTimeMillis()
  }
}

Schedule Repeatedly

To schedule sending of a message to an actor or execution of task repeatedly over a certain interval. We’ll use the schedule method provided by the Scheduler. Here’s an example:

object ScheduleRepeatedlyExample extends App {
  val system = ActorSystem("AkkaSchedulerExample")
  val simpleActor = system.actorOf(Props[SimpleActor])

  //Use the system's dispatcher as ExecutionContext
  import system.dispatcher

  //This will schedule to send a message after 1 second of initial delay, 
  //repeating every 2 second(interval)
  val scheduleRepeatedly = system.scheduler.schedule(1 seconds, 2 seconds){
    simpleActor ! "I'm waiting! Please respond"
  }
}

Canceling a Schedule

When we create a schedule, it returns a Cancellable instance. We can use this instance to cancel an active schedule:

val scheduleRepeatedly: Cancellable = system.scheduler.schedule(1 second, 2 seconds) {
  simpleActor ! "I'm waiting! Please respond"
}

// This will cancel the repeated schedule after 5 seconds
system.scheduler.scheduleOnce(5 seconds) {
  scheduleRepeatedly.cancel() // cancel repeated schedule
}

That’s it. I hope you found this blog easy to understand and useful. For more blogs related to Scala and Akka, visit Knoldus Blogs.

References

Akka Documentation – Scheduler

knoldus

Written by 

Prateek Gupta is a Software Consultant at Knoldus Inc. He likes to explore new technologies and believes in writing clean code. He has a good understanding of programming languages like Java and Scala. He also has good time management skills. In his leisure time, he like to do singing and watch SciFi movies.