在执行过程中停止 Rhino 引擎

2024-03-09

Rhino 引擎是否有一个 api 可以停止执行 脚本fie在中间。例如,我有一个脚本文件,其中 有一个无限循环。怎样才能中途停止执行呢?

当然,我可以停止启动Rhino引擎的jvm 执行脚本。但我不想因为这个原因终止整个 jvm 会话,因为我已经以编程方式启动了脚本,并且 Rhino 引擎也与我的应用程序在同一个 JVM 中运行。


可以通过以下方式停止正在运行的 JavaScript 的执行。

1) 创建一个虚拟调试器并将其附加到最初创建的上下文。

mContext = Context.enter();
ObservingDebugger 观察调试器 = new ObservingDebugger();
mContext.setDebugger(observingDebugger, new Integer(0));
mContext.setGenerateDebug(true);
mContext.setOptimizationLevel(-1);

ObservingDebugger 代码如下所示。

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.debug.DebugFrame;
import org.mozilla.javascript.debug.DebuggableScript;
import org.mozilla.javascript.debug.Debugger;

public class ObservingDebugger implements Debugger 
{
boolean isDisconnected = false;

private DebugFrame debugFrame = null;

public boolean isDisconnected() {
    return isDisconnected;
}

public void setDisconnected(boolean isDisconnected) {
    this.isDisconnected = isDisconnected;
    if(debugFrame != null){
       ((ObservingDebugFrame)debugFrame).setDisconnected(isDisconnected);
    }
}

public ObservingDebugger() {

}

public DebugFrame getFrame(Context cx, DebuggableScript fnOrScript)
{
    if(debugFrame == null){
        debugFrame = new ObservingDebugFrame(isDisconnected);
    }
    return debugFrame;      
}

@Override
public void handleCompilationDone(Context arg0, DebuggableScript arg1, String arg2) {   } }
// internal ObservingDebugFrame class
class ObservingDebugFrame implements DebugFrame
   {
boolean isDisconnected = false;

public boolean isDisconnected() {
    return isDisconnected;
}

public void setDisconnected(boolean isDisconnected) {
    this.isDisconnected = isDisconnected;
}

ObservingDebugFrame(boolean isDisconnected)
{
    this.isDisconnected = isDisconnected;
}

public void onEnter(Context cx, Scriptable activation,
        Scriptable thisObj, Object[] args)
{ }

public void onLineChange(Context cx, int lineNumber) 
{
    if(isDisconnected){
        throw new RuntimeException("Script Execution terminaed");
    }
}

public void onExceptionThrown(Context cx, Throwable ex)
{ }

public void onExit(Context cx, boolean byThrow,
        Object resultOrException)
{ }

@Override
public void onDebuggerStatement(Context arg0) { } }

ObservingDebugger 类将管理布尔变量“isDisconnected”,当用户单击停止按钮(想要停止执行)时,该变量将设置为 true。一旦变量设置为 true,如下所示,Rhino 执行将立即终止。

observingDebugger.setDisconnected(true);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在执行过程中停止 Rhino 引擎 的相关文章

随机推荐