Schedule a Job in Play with Akka


Greetings to all ,

In this blog we will see how we can schedule a job after some time period in play using Scala .

I assume that reader of this blog have little knowledge about :

  • Akka
  • Play and
  • Scala

So here we start with an actor where we will write our job to be scheduled as follow :

import javax.inject.{Inject, Singleton}
import akka.actor.Actor
import play.api.Logger
import scala.concurrent.ExecutionContext
@Singleton
class JobSchedulerActor @Inject()(implicit ec: ExecutionContext) extends Actor{
var c= 0
override def receive: Receive = {
case _ =>
c = c+1
Logger.info("Job Scheduled "+ c )
//Here put your code for your job
}
}

Now we will define scheduler for the above job to execute at certain duration as follow :

class Scheduler @Inject() (val system: ActorSystem, @Named("<strong>JobSchedulerActor</strong>") val j<strong>obSchedulerActor</strong>: ActorRef)(implicit ec: ExecutionContext) {
var actor = system.scheduler.schedule(
0.seconds, 30.seconds,JobSchedulerActor, "schedule")
}

Now we need to bind the above actor and scheduler as :

import actor.SchedulerActor
import com.google.inject.AbstractModule
import play.api.Logger
import play.api.libs.concurrent.AkkaGuiceSupport
import scheduler.Scheduler

class BindModule extends AbstractModule with AkkaGuiceSupport {
def configure() = {
Logger.info("\nConfigurring Scheduler.")
bindActor[<strong>JobSchedulerActor</strong>]("<strong>JobSchedulerActor</strong>")
bind(classOf[Scheduler]).asEagerSingleton()
}
}

Now tell the play to start the actor after schedule time. We only need to write following configuration inside application.conf :

play.modules.enabled += "modules.BindModule"

And now cheers 🙂 your scheduler will start scheduling your job after specified duration once your server is up .

Thanks

KNOLDUS-advt-sticker

Advertisements

About Rahul Kumar

Software Consultant At Knoldus
This entry was posted in Scala. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s