Sakib Sami' Blog


Newbie programmer, Java fan, Rosogolla lover, Mom's little kid.


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 {

    @Override
    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),
                    Akka.system().actorOf(Props.create(SchedulerActor.class)),
                    "Hello Actor",
                    Akka.system().dispatcher(),
                    null
            );

// 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.
or

Akka.system().stop(Akka.system().actorOf(Props.create(SchedulerActor.class)));  

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

You need to know, to begin as software engineer

Fortunately I had the opportunity to face few interviews. And this article is a sum up of what compa…

Experimenting Uber Like Application Architecture

Hello, Good people. Hope you all are fine. You may hear about Uber, Grab, Pathao or other ride shari…

uber, mqtt, grab, pathao, lyft, ride sharing app, mongodb