且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Groovy Shell脚本对象未完全执行

更新时间:2023-12-05 14:18:04

当您同时在不同线程中运行同一脚本实例时,仅通过脚本逻辑即可停止该脚本实例.

when you run the same instance of Script in different threads at the same time it could be stopped just by logic of your script.

如果要缓存已解析的脚本,则将已解析的类而不是脚本的实例存储到映射中,并针对每次运行重新绑定变量.

if you want ta cache the parsed script, then store into your map the parsed class and not the instance of script and for each run re-bind variables.

以下代码段应为您提供一个实现方法:

the following code snippet should give you an idea how to do that:

scriptMap = new HashMap()

Script getScript(String code){
    Class<Script> scriptClass = scriptMap.get(code);
    if(scriptClass)return script.newInstance();
    GroovyShell shell = new GroovyShell(); 
    Script script = shell.parse( code );
    scriptMap.put(code, script.getClass());
    return script;
}

Object runScript(String code, Map variables){
    Script script=getScript(code);
    script.setBinding( new Binding(variables) );
    return script.run();
}

println runScript("a+b", [a:2,b:7])
println runScript("(b-a)*3", [a:7,b:9])
println scriptMap