How to execute on start code in scala Play! framework application?

做~自己de王妃 提交于 2019-12-04 20:42:21

问题


I need to execute a code allowing the launch of scheduled jobs on start of the application, how can I do this? Thanks.


回答1:


Use the Global object which - if used - must be defined in the default package:

object Global extends play.api.GlobalSettings {

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

}

Remember that in development mode, the app only loads on the first request, so you must trigger a request to start the process.


Since Play Framework 2.6x

The correct way to do this is to use a custom module with eager binding:

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()
  }
}

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




回答2:


I was getting a similar error. Like @Leo said, create Global object in app/ directory.

Only thing I had to make sure was to change "app: Application" to "app: play.api.Application".

app: Application referred to class Application in controllers package.



来源:https://stackoverflow.com/questions/14631827/how-to-execute-on-start-code-in-scala-play-framework-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!