How to define arbitrary tasks in the Play Framework?
I mean tasks run from the command line, something similar to ruby rake.
I'm aware of the ant tool but looking for a better alternative.
For Play 2, you can create new tasks using SBT, by following the documentation here:
http://www.scala-sbt.org/release/docs/Detailed-Topics/Tasks
In the context of a Play 2 generated Build.scala, it might look like this:
import sbt._
import Keys._
import play.Project._
object ApplicationBuild extends Build { 
  val appName         = "foo"
  val appVersion      = "1.0-SNAPSHOT"
  val appDependencies = Seq(
    // Add your project dependencies here,
    jdbc,
    anorm
  )
  val hello = TaskKey[Unit]("hello", "Prints 'Hello World'")
  val helloTask = hello := {
    println("Hello World")
  }
  lazy val main = play.Project(appName, appVersion, appDependencies).settings(
    helloTask
  )
}
[edit] This answer is for the Play 1.* series!
You should write a custom module, then your commands go into the commands.py file, ref: http://www.playframework.org/documentation/1.2.4/releasenotes-1.1#commands
You can look at existing modules to get inspired, eg: https://github.com/sim51/logisima-play-yml/blob/master/commands.py
Basically you define the commands you want and launch them from the "execute" method, eg:
COMMANDS = ['namespace:command']
def execute(**kargs):
    command = kargs.get("command")
    app = kargs.get("app")
    args = kargs.get("args")
    env = kargs.get("env")
    if command == "namespace:command":
        do_something()
if you want to launch something java - often the case! -:
def do_something():
    java_cmd = app.java_cmd([], None, "play.modules.mymodule.MyClass", args)
        try:
            subprocess.call(java_cmd, env=os.environ)
        except OSError:
            print "Could not execute the java executable, please make sure the JAVA_HOME environment variable is set properly (the java executable should reside at JAVA_HOME/bin/java). "
            sys.exit(-1)
        print
Ps.
creating a custom module is as easy as:
play new-module mymodule
This is a primer: http://playframework.wordpress.com/2011/02/27/play-modules/ , considering that official Play! module documentation is quite limited in that respect
edit
I thought I'd add a little piece of information:
before being able to execute your commands, you must BUILD your module. It does not run like the rest of play with a dynamic compilation.
play build-module mymodule
new-module/build-module expect the module to be at the root of the project folder, but if you have many that becomes a mess. build-module module-srcs/mymodule works perfectly fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With