使用应用程序上下文播放2.4.x Akka调度程序

时间:2016-06-16 19:41:16

标签: scala playframework akka playframework-2.4

我试图在play framework 2.4.x中创建一个调度程序。我能够创建调度程序,但无法配置当前的应用程序环境。

基本上,调度程序应该执行控制器方法或调用URL。

到目前为止,我得到了这个:

object Global extends GlobalSettings {

  override def onStart(app: Application) {
    System.out.println("App Started");
    import play.api.Play.current
    var delayInSeconds: Long = 0l;

    var c: Calendar = Calendar.getInstance();
    c.set(Calendar.HOUR_OF_DAY, current.configuration.getInt("application.execution.hour").getOrElse(8))
    c.set(Calendar.MINUTE, current.configuration.getInt("application.execution.min").getOrElse(0))
    c.set(Calendar.SECOND, 0);

    var plannedStart: Date = c.getTime();
    var now: Date = new Date();
    var nextRun: Date = null;
    if (now.after(plannedStart)) {
      c.add(Calendar.DAY_OF_WEEK, 1);
      nextRun = c.getTime();
    } else {
      nextRun = c.getTime();
    }
    delayInSeconds = (nextRun.getTime() - now.getTime()) / 1000; //To convert milliseconds to seconds.

    var delay: FiniteDuration = Duration(delayInSeconds, TimeUnit.SECONDS);
    var frequency: FiniteDuration = Duration(1, TimeUnit.DAYS);

    val schedulerActor = Akka.system(app).actorOf(Props[SchedulerActor], name = "schedulerActor")

    Akka.system(app).scheduler.schedule(delay, frequency, schedulerActor, Scheduler);
  }
}

case object Scheduler

class SchedulerActor extends Actor {

  def receive = {
    case Scheduler => executeSchedulerWorkflows
  }

  def executeSchedulerWorkflows = {

  }
}

内部def executeSchedulerWorkflows我想做类似的事情:

def executeSchedulerWorkflows = {
    WS.client(url)
}

注入WS。怎么做?

1 个答案:

答案 0 :(得分:1)

你可以不在GlobalSettings上做(不推荐使用)。 通常我这样做:

  1. 创建模块

    class YourModule extends Module {
      override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = 
     Seq(bind[Init].toSelf.eagerly())
     }
    
  2. 注意:正如您所看到的,存在与Init ...

    的绑定
    1. 创建Init类

       class Init @Inject()(application: Application, actorSystem: ActorSystem//Here you can inject whatever you want) {
      
       //TODO //Here you create the actor with all it's dependencies
      
       // or use directly the scheduler of the actorSystem
       actorSystem.scheduler.schedule(0.seconds,1.day){
      
           //Your stuff
      
       }
      

      }

    2. 注册该模块

       play.modules.enabled += "somepackage.YourModule"