/ play

PlayFramework Scheduler with Akka

Play is a JVM based framework to develop robust, highly concurrent web application written on Scala programming language.

Akka is a JVM based framework to develop concurrent, distributed and message driven application written in Scala.

Play Framework included Akka to handle concurrency and other related tasks.

This tutorial is to show you, how you can write a scheduling task in Play Framework using Akka.

What is scheduled task ?
Sometimes in application we need to do some task on a specific time interval like cleaning garbage data from db or collecting data from internet etc.

Lets say the scheduler will clean Session table from db on 10 seconds interval.

First we need a actor todo the task. Lets write a actor.

import akka.actor.UntypedActor;
import play.Logger;

public class SchedulerActor extends UntypedActor {
    public void onReceive(Object message) throws Exception {
        Logger.debug("onReceive called.");
        // doDBCleanUpHere();

And schedule the task,

Cancellable cancellable = Akka.system().scheduler().schedule(
                    Duration.create(5, TimeUnit.SECONDS),
                    Duration.create(10, TimeUnit.SECONDS),
                    "Hello Actor",

// schedule(waiting_time_to_start, interval_time_for_repeated_execution, actor_model, message_to_receiver, dispatcher, sender)

Now scheduler will start working after 5 seconds of initialization and on every 10 seconds interval will call onReceive() method of SchedulerActor class. onReceive() method will be executed synchronously. If you do any long running task, new calls will be queued till the completion of previous task.

Call cancellable.cancel() to stop.


You can implement Actor class instead of reusing UntypedActor to implement everything by yourself.