How to correctly schedule task in Play Framework 2

2019-01-24 11:32发布

问题:

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?

回答1:

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



回答2:

Try

context.system.scheduler.schedule

And also make sure you have logging at Debug level otherwise those messages won't make it to the console. If you're unsure try changing them to Logger.error temporarily.