简体   繁体   English

Scala Play 2.4在应用程序启动时运行akka Scheduler服务

[英]Scala Play 2.4 run akka scheduler service on Application start

I want to use Akka scheduler to do some cron jobs in my Play application. 我想使用Akka调度程序在Play应用程序中执行某些cron作业。

Since Play 2.4 GlobalSettings is not recommended. 由于不建议使用Play 2.4 GlobalSettings。 Anyone has some sample code on how to do that? 任何人都有一些有关如何执行此操作的示例代码?

Even I tried the simple code from Play docs and it still not working. 即使我尝试了Play文档中的简单代码,仍然无法正常工作。

class CustomApplicationLoader extends GuiceApplicationLoader() {
  val logger: Logger = Logger(this.getClass)

  override def builder(context: ApplicationLoader.Context): GuiceApplicationBuilder = {
    logger.info("start")
    val extra = Configuration("a" -> 1)
    initialBuilder
      .in(context.environment)
      .loadConfig(extra ++ context.initialConfiguration)
      .overrides(overrides(context): _*)
  }
}

play.application.loader = "com.xxx.CustomApplicationLoader"

Why I can't get the logging message to print? 为什么我无法打印日志消息?

How I can use Akka on Application start? 如何在应用程序启动时使用Akka?

This is how do it in my app: 这是我的应用程序中的操作方法:

Start of by defining a trait Scheduled. 首先定义一个预定的特征。

package scheduled

import akka.actor.Cancellable

trait Scheduled {

  var cancellable: Option[Cancellable] = None

  val defaultInterval = 60
  val secondsToWait = {
    import scala.concurrent.duration._
    10 seconds
  }

  def start()
  def stop() = {
    cancellable.map(_.cancel())
  }
}

Then implement Scheduled with Akka magic 然后用Akka Magic实施Scheduled

package scheduled

import akka.actor.ActorSystem
import play.api.{Configuration, Logger}
import com.google.inject.{Singleton, Inject}
import play.api.libs.concurrent.Execution.Implicits._

trait ScheduledWorker extends Scheduled

@Singleton
class ScheduledWorkerImpl @Inject()(
                                                  actorSystem: ActorSystem,
                                                  configuration: Configuration

                                                  ) extends ScheduledWorker {
  start()

  lazy val intervalKey = "worker.interval"
  lazy val jobEnabled = "worker.enabled"

  override def start(): Unit = {
    import scala.concurrent.duration._
    lazy val i = configuration.getInt(intervalKey).getOrElse(defaultInterval)
    lazy val isEnabled = Option(System.getProperty(jobEnabled)).getOrElse(
      configuration.getString(jobEnabled).getOrElse("false")
    ).equals("true")

    cancellable = isEnabled match {
      case true =>
        Some(
          actorSystem.scheduler.schedule(0 seconds, i minutes) {
            .. MAJOR COOL CODE!!! ;))) ...
          }
        )
      case _ => None
    }
  }
}

create a module to eagerly start the scheduled stuff 创建一个模块以热切地启动计划的工作

package modules

import play.api.{Configuration, Environment}
import play.api.inject.Module
import scheduled.{ScheduledWorker}

class ScheduledModule extends Module {

  def bindings(environment: Environment,
               configuration: Configuration) = Seq(
      bind[ScheduledWorker].to[ScheduledWorkerImpl].eagerly()
    )
}

make sure that your config specifies ScheduledModule. 确保您的配置指定ScheduledModule。

play.modules.enabled += "modules.ScheduledModule"

And voila you have a working scheduled task when your play 2.4 app starts =) 瞧,当您播放2.4应用启动时,您有一个正在执行的预定任务=)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM