JRuby:如果运行时间太长就关闭 runScriptlet?
JRuby: closing runScriptlet if it takes too long?
我想使用 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
由于我使用的是已弃用的方法,因此我不会将此标记为官方答案。
我想使用 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
由于我使用的是已弃用的方法,因此我不会将此标记为官方答案。