Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly schedule task in Play Framework 2.4.2 scala?

Trying to schedule tasks like this in Play Framework 2.4.2 Scala without luck:

import akka.actor.Actor
import play.api.libs.concurrent.Akka
import scala.concurrent.duration._
import play.api.Play.current
import scala.concurrent.ExecutionContext.Implicits.global

class Scheduler extends Actor {

  override def preStart() {
    val dbupdate = Akka.system.scheduler.schedule(
      0.microseconds, 5.minutes, self, "update")
    val pictureClean = Akka.system.scheduler.schedule(
      0.microseconds, 30.minutes, self, "clean")
  }

  def receive = {
    case "update" => updateDB()
    case "clean" => clean()
  }

  def updateDB(): Unit ={
    Logger.debug("updates running")
  }

  def clean(): Unit ={
    Logger.debug("cleanup running")
  }
}

Nothing is printed in console. What I'm doing wrong?

like image 505
sergeda Avatar asked Jul 28 '15 14:07

sergeda


1 Answers

Ok. Here working code of scheduler I've built: Module:

class JobModule extends AbstractModule with AkkaGuiceSupport {
  def configure() = {
    bindActor[SchedulerActor]("scheduler-actor")
    bind(classOf[Scheduler]).asEagerSingleton()
  }
}

Scheduler:

class Scheduler @Inject() (val system: ActorSystem, @Named("scheduler-actor") val schedulerActor: ActorRef)(implicit ec: ExecutionContext)
{
  system.scheduler.schedule(
    0.microseconds, 5.minutes, schedulerActor, "update")
  system.scheduler.schedule(
    30.minutes, 30.days, schedulerActor, "clean")
}

Actor:

@Singleton
class SchedulerActor @Inject() (updater: Updater) extends Actor {
  def receive = {
    case "update" => updateDB()
    case "clean" => clean()
  }

  def updateDB(): Unit ={
    Logger.debug("updates running")
  }

  def clean(): Unit ={
    Logger.debug("cleanup running")
  }
}

You also need to add your module in application.conf:

play.modules.enabled += "modules.JobModule"

Hope this will help someone

like image 181
sergeda Avatar answered Oct 22 '22 16:10

sergeda