我们正在使用 Rhino 在 Java 应用程序中执行 Javascript。我们使用一些特定于 Rhino 的功能,因此无法升级到 Nashorn。 我们遇到的问题是,脚本是由用户创建的,当我们执行它们时,如果出现无限循环之类的错误,它就会永远执行下去。我们想设置一个 30 秒之类的时间限制。 有没有办法在超时时终止脚本?
最佳答案
您应该扩展ContextFactory
类并重写方法observeInstructionCount(Context ctx, int instructionsCount)
。 Rhino 会定期调用此方法,您可以通过以下方式检查到目前为止它已经运行了多长时间:
public class ScriptDynamicScopeFactory extends ContextFactory {
@Override
protected Context makeContext() {
ScriptContext ctx = new ScriptContext();
ctx.setInstructionObserverThreshold(10000);
return ctx;
}
@Override
protected void observeInstructionCount(Context ctx, int instructionCount) {
long currentTime = System.currentTimeMillis();
long executionTime = (currentTime - ((ScriptContext) ctx).startTime());
// do something if execution time is greater then your timeout
}
}
请注意,您还需要重写 makeContext()
以设置调用观察者的频率。请记住,这是执行的指令数,这意味着它不会每 X 毫秒一致地调用一次。如果一条指令需要很多时间(例如,调用您的 Java 应用程序),这可能效果不佳,但我认为它在几乎所有情况下都会做得很好。
关于java - 如何杀死 Rhino 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57275093/