如何在scala Play中启动代码!框架申请?

问题描述 投票:8回答:2

我需要执行一个代码,允许在应用程序启动时启动预定作业,我该怎么做?谢谢。

scala playframework-2.0 scheduled-tasks startup
2个回答
14
投票

使用Global对象 - 如果使用 - 必须在默认包中定义:

object Global extends play.api.GlobalSettings {

  override def onStart(app: play.api.Application) {
    ...
  }

}

请记住,在开发模式下,应用程序仅在第一个请求时加载,因此您必须触发启动该过程的请求。


自Play Framework 2.6x起

执行此操作的正确方法是使用具有急切绑定的自定义模块:

import scala.concurrent.Future
import javax.inject._
import play.api.inject.ApplicationLifecycle

// This creates an `ApplicationStart` object once at start-up and registers hook for shut-down.
@Singleton
class ApplicationStart @Inject() (lifecycle: ApplicationLifecycle) {

  // Start up code here

  // Shut-down hook
  lifecycle.addStopHook { () =>
    Future.successful(())
  }
  //...
}
import com.google.inject.AbstractModule

class StartModule extends AbstractModule {
  override def configure() = {
    bind(classOf[ApplicationStart]).asEagerSingleton()
  }
}

https://www.playframework.com/documentation/2.6.x/ScalaDependencyInjection#Eager-bindings


0
投票

我收到了类似的错误。就像@Leo所说,在app /目录中创建Global对象。

我唯一需要确定的是将“app:Application”更改为“app:play.api.Application”。

app:应用程序在控制器包中引用类Application。

© www.soinside.com 2019 - 2024. All rights reserved.