Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 727
Peter Avatar asked Jan 31 '13 17:01

Peter


People also ask

How do I run a debug in play framework?

Generate configuration To debug, start your application with activator -jvm-debug 9999 run and in Eclipse right-click on the project and select Debug As, Debug Configurations. In the Debug Configurations dialog, right-click on Remote Java Application and select New. Change Port to 9999 and click Apply.

How do I run in production mode?

The easiest way to start an application in production mode is to use the start command from the Play console. This requires a Play installation on the server. When you run the start command, Play forks a new JVM and runs the default Netty HTTP server.


1 Answers

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

like image 182
Leo Avatar answered Nov 15 '22 23:11

Leo