我想使用 JRuby 来运行 Ruby 脚本。
但是,我希望如果脚本花费的时间超过 t
秒,它将自动关闭。
这是我的尝试:
ScriptingContainer ruby = new ScriptingContainer();
int t = 3;
new Thread() {
@Override
public void run() {
try {
Thread.sleep(t * 1000); // Timeout
System.out.println("Timeout passed.");
ruby.terminate(); // This has no effect?
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
Object output = ruby.runScriptlet(scriptWithAnInfiniteLoop);
ruby.terminate(); // Terminate without timeout, at the end of the script
最佳答案
这是使用已弃用 Thread.stop()
的答案:
ScriptingContainer ruby = new ScriptingContainer();
int t = 5;
String script = content;
Thread runner = new Thread() {
@Override
public void run() {
try {
ruby.runScriptlet(script);
ruby.terminate(); // Close normally.
} catch (Exception e) {
ruby.terminate(); // Close if JRuby crashes.
}
}
};
Thread killer = new Thread() {
@Override
public void run() {
try {
Thread.sleep(t * 1000);
runner.stop();
ruby.terminate(); // Close forcefully.
} catch (Exception e) {}
}
};
runner.start();
killer.start();
请参阅这篇文章,了解它为何被弃用:https://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html
由于我使用的是已弃用的方法,因此我不会将此标记为官方答案。
关于java - JRuby:如果运行时间太长,请关闭 runScriptlet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56813020/