In the Play documentation, we see how to hook in to the Play application’s life cycle with Global’s onStart, onStop, etc. However, sometimes you want to hook into the Play sbt plugin lifecycle for development or build purposes. Most usefully, you may want to run another task or process every time Play compiles, starts up (pre-Global), or stops (post-Global).
If you want to simply hook into the sbt compile step, you can do so before or after:
// Define your task val yourCompileTask = TaskKey[Unit]("Your compile task") val yourProject = play.Project("yourApp", "1.0").settings( // Example using a sbt task: yourCompileTask := { println("++++ sbt compile start!") }, (compile in Compile) <<= (compile in Compile) dependsOn (yourCompileTask), // Or just running Scala code: (compile in Compile) <<= (compile in Compile) map { result => println(s"++++ sbt compile end: $result") result } ) |
More powerful, however, is to create a PlayRunHook:
object SimplePlayRunHook { import java.net.InetSocketAddress import play.PlayRunHook def apply(base: File): PlayRunHook = { new PlayRunHook { override def beforeStarted(): Unit = { println(s"++++ simplePlayRunHook.beforeStarted: $base") } override def afterStarted(address: InetSocketAddress): Unit = { println(s"++++ simplePlayRunHook.afterStarted: $address, $base") } override def afterStopped(): Unit = { println("++++ simplePlayRunHook.afterStopped") } } } } val yourProject = play.Project("yourApp", "1.0").settings( playRunHooks <+= baseDirectory.map(base => SimplePlayRunHook(base)) ) |
Here’s what it looks like with both:
[kifi-backend] $ compile ++++ sbt compile start! ++++ sbt compile: Analysis: 3 Scala sources, 8 classes, 24 external source dependencies, 5 binary dependencies [success] Total time: 8 s, completed Mar 3, 2014 11:51:16 AM [kifi-backend] $ run ++++ simplePlayRunHook.beforeStarted: /Users/andrew/Documents/workspace/kifi/kifi-backend --- (Running the application from SBT, auto-reloading is enabled) --- [info] play - Listening for HTTP on /0:0:0:0:0:0:0:0:9000 ++++ simplePlayRunHook.afterStarted: /0:0:0:0:0:0:0:0:9000, /Users/andrew/Documents/workspace/kifi/kifi-backend (Server started, use Ctrl+D to stop and go back to the console...) ++++ simplePlayRunHook.afterStopped [success] Total time: 12 s, completed Mar 3, 2014 11:51:32 AM
A common use case of these hooks is to trigger an auxiliary build process, like for a compiles-to-JS language or build tool such as Gulp/Grunt.