【问题标题】:Play 2.4.x Akka scheduler with application context使用应用程序上下文播放 2.4.x Akka 调度程序
【发布时间】:2023-03-06 22:53:02
【问题描述】:

我正在尝试在 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。该怎么做?

【问题讨论】:

    标签: scala playframework akka playframework-2.4


    【解决方案1】:

    您可以通过不在GlobalSettings 上执行此操作(已弃用)来执行此操作。 通常我会这样做:

    1. 创建一个模块

      class YourModule extends Module {
        override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = 
       Seq(bind[Init].toSelf.eagerly())
       }
      

    注意:如您所见,有一个与 Init 的绑定...

    1. 创建初始化类

       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"
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-14
      • 1970-01-01
      • 2012-08-17
      • 2014-02-23
      • 1970-01-01
      • 2013-08-02
      • 2018-01-01
      相关资源
      最近更新 更多