使用应用程序上下文播放 2.4.x Akka 调度程序
Posted
技术标签:
【中文标题】使用应用程序上下文播放 2.4.x Akka 调度程序【英文标题】:Play 2.4.x Akka scheduler with application context 【发布时间】:2016-06-16 19:41:16 【问题描述】:我正在尝试在 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】:您可以通过不在GlobalSettings
上执行此操作(已弃用)来执行此操作。
通常我会这样做:
创建一个模块
class YourModule extends Module
override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] =
Seq(bind[Init].toSelf.eagerly())
注意:如您所见,有一个与 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
注册该模块
play.modules.enabled += "somepackage.YourModule"
【讨论】:
以上是关于使用应用程序上下文播放 2.4.x Akka 调度程序的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Scala Akka 中停止 system.scheduler.schedule