【问题标题】:JRuby: closing runScriptlet if it takes too long?JRuby:如果运行时间过长,是否关闭 runScriptlet?
【发布时间】:2019-06-29 05:10:56
【问题描述】:

我想使用 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

【问题讨论】:

    标签: java ruby multithreading jruby thread-sleep


    【解决方案1】:

    这是使用已弃用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

    由于我使用的是已弃用的方法,因此我不会将此标记为官方答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-02
      • 1970-01-01
      • 2020-04-16
      相关资源
      最近更新 更多