如何从我的Grails应用程序执行Groovy脚本?

时间:2009-12-18 10:28:03

标签: grails scripting groovy

嗯,这似乎是一个简单的任务,但我没有设法让它运行。

我有一个groovy脚本,在提示符调用时在Windows Vista下正常运行:

> cd MY_GAILS_PROJECT_DIR
> groovy cp src/groovy scripts/myscript.groovy

现在,我想通过我的维护服务类(从控制器调用)执行此脚本(并向其传递一些输入参数),如下所示,

class MaintenanceService {
  def executeMyScript() {
    "groovy cp src/groovy scripts/myscript.groovy".execute()
  }
}

根本不起作用!我甚至没有设法让execute()方法识别任何命令(如"cd .".execute())抛出异常:

Error 500: java.io.IOException: Cannot run program "cd": CreateProcess error=2, The system cannot find the file specified

1-如何从grails应用程序执行groovy脚本?

2-这里有哪些最佳做法?例如,我应该使用QuartzPlugin然后使用triggerNow方法来执行脚本吗?我应该使用Gant任务吗?如果是的话,该怎么做?

谢谢。

5 个答案:

答案 0 :(得分:5)

如果您不介意您的脚本异步运行(在与服务方法分开的过程中),假设您的PATH变量上有groovy,则以下情况应该有效:

def cmd = ['groovy.bat', 'cp', 'src/groovy scripts/myscript.groovy']
cmd.execute()

如果你想在应用程序控制台中查看进程的输出,你应该尝试这样的事情

// Helper class for redirecting output of process
class StreamPrinter extends Thread {
    InputStream inputStream

    StreamPrinter(InputStream is) {
        this.inputStream = is
    }

    public void run() {
        new BufferedReader(new InputStreamReader(inputStream)).withReader {reader ->
            String line
            while ((line = reader.readLine()) != null) {
                println(line)
            }
        }
    }
}

// Execute the script
def cmd = ['groovy', 'cp', 'src/groovy scripts/myscript.groovy']
Process executingProcess = cmd.execute()

// Read process output and print on console
def errorStreamPrinter = new StreamPrinter(executingProcess.err)
def outputStreamPrinter = new StreamPrinter(executingProcess.in)
[errorStreamPrinter, outputStreamPrinter]*.start()

<强>更新 在回复下面的评论时,请尝试以下操作(假设您使用的是Windows):

1:创建文件C:\ tmp \ foo.groovy。该文件的内容应该是:

println 'it works!'

2:在groovy控制台中,运行以下命令:

cmd = ['groovy.bat', 'C:\\tmp\\foo.groovy']
cmd.execute().text

3:您应该看到Groovy控制台中显示的脚本结果(文本'it works!')

如果您无法使用这个简单的示例,那么您的环境就会出现问题,例如: 'groovy.bat'不在你的路径上。如果你能让这个例子有效,那么你应该能够从中做出努力来实现你的目标。

答案 1 :(得分:4)

从Grails 1.3.6开始,内置run-script命令可让您运行

grails run-script myScript.groovy

对于早期版本的grails,check out my updated blog post来自Carlos上面发布的内容。

答案 2 :(得分:2)

最简单的方法:

生成一个Groovy类并放在Grails项目的/ src / groovy文件夹中。 在您的域类中导入该类并使用您定义的函数。

我的2分......

答案 3 :(得分:0)

答案 4 :(得分:0)

您可以使用 GroovyScriptEngine 的另一个决定,例如:

文件 MyScript.groovy:

static String showMessage() {
    println("Message from showMessage")
}

文件 BootStrap.groovy:

class BootStrap {

    def init = { servletContext ->
        new GroovyScriptEngine("scripts")
                .loadScriptByName("MyScript.groovy")
                .showMessage()
    }
    def destroy = {

    }
}