How to correctly schedule task in Play Framework 2.4.2 scala?

隐身守侯 提交于 2019-11-27 21:50:10

问题


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.



来源:https://stackoverflow.com/questions/31679563/how-to-correctly-schedule-task-in-play-framework-2-4-2-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!