How to create scheduled asynchronous jobs in playframework 2

290 Flares Twitter 0 Facebook 0 Google+ 290 LinkedIn 0 Filament.io 290 Flares ×

Scheduling jobs is easy and straightforward in playframework 2. Let us look at how we can create scheduled  asynchronous jobs in playframework 2.

Play uses the Akka system for running tasks. Akka 2.0 works with containers known as ActorSystems.An actor system manages the resources it is configured to use in order to run the actors it contains.By default play provides a system actor. The official documentation says “A Play application defines a special actor system to be used by the application. This actor system follows the application life-cycle and restarts automatically when the application restarts”.

Hence for running jobs we can utilize the default Actor System provided by play. Since the Actor System is already available, we just need to create an Actor and configure it to run at specified intervals.

Let us take a hello world example to see how we can schedule a job at application start up, running at 30 minute intervals, always. Steps for these are as follows

  1. Create the actor
  2. Create a Global Object to configure the job

The actor is now ready. The next step is to configure the job to run at a specified interval. We want the job to start running as soon as the application is started. For this we can utilize the Application Global Object provided by the playframework. The playframework will now call the configured actor’s onReceive method in 5 minute intervals. Please note that this Global class should be at the root of your source code and not within any packages. Play documentation says “This object must be defined in the root package.”.

  • cloverich

    Nice, short explanation. Official docs attempt to explain the same thing – but reference an Actor thats not defined on the same page; easy to forget how confusing this is to someone who has never used Akka before and is unfamiliar with actors. This is how they should explain it.

  • testy

    I am trying this but if I add Thread.sleep(10000) in onReceive and schedule the actor each second the next call to onReceive is after the sleep finishes (10 seconds instead of 1). This means it is not really async or am I making a mistake?