如何包装一个方法,以便在超过指定的超时时终止它的执行? [英] How can I wrap a method so that I can kill its execution if it exceeds a specified timeout?

查看:21
本文介绍了如何包装一个方法,以便在超过指定的超时时终止它的执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法要调用.但是,我正在寻找一种干净、简单的方法来杀死它或在执行时间过长时强制它返回.

I have a method that I would like to call. However, I'm looking for a clean, simple way to kill it or force it to return if it is taking too long to execute.

我使用的是 Java.

I'm using Java.

举例说明:

logger.info("sequentially executing all batches...");
for (TestExecutor executor : builder.getExecutors()) {
logger.info("executing batch...");
executor.execute();
}

我认为 TestExecutor 类应该实现 Callable 并继续朝着这个方向发展.

I figure the TestExecutor class should implement Callable and continue in that direction.

但我想要做的就是停止 executor.execute() 如果它花费的时间太长.

But all i want to be able to do is stop executor.execute() if it's taking too long.

建议...?

编辑

收到的许多建议假设执行的方法需要很长时间,包含某种循环,并且可以定期检查变量.然而,这种情况并非如此.所以有些东西不一定是干净的,只会在可接受的地方停止执行.

Many of the suggestions received assume that the method being executed that takes a long time contains some kind of loop and that a variable could periodically be checked. However, this is not the case. So something that won't necessarily be clean and that will just stop the execution whereever it is is acceptable.

推荐答案

你应该看看这些类:FutureTask可调用执行器

You should take a look at these classes : FutureTask, Callable, Executors

这是一个例子:

public class TimeoutExample {
    public static Object myMethod() {
        // does your thing and taking a long time to execute
        return someResult;
    }

    public static void main(final String[] args) {
        Callable<Object> callable = new Callable<Object>() {
            public Object call() throws Exception {
                return myMethod();
            }
        };
        ExecutorService executorService = Executors.newCachedThreadPool();

        Future<Object> task = executorService.submit(callable);
        try {
            // ok, wait for 30 seconds max
            Object result = task.get(30, TimeUnit.SECONDS);
            System.out.println("Finished with result: " + result);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        } catch (TimeoutException e) {
            System.out.println("timeout...");
        } catch (InterruptedException e) {
            System.out.println("interrupted");
        }
    }
}

这篇关于如何包装一个方法,以便在超过指定的超时时终止它的执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆