问题描述
我有一个方法,我想打电话。但是,我正在寻找一个干净,简单的方法来杀死它或强制它返回,如果它需要太长的执行。
我使用Java。
说明:
logger.info批次...);
for(TestExecutor executor:builder.getExecutors()){
logger.info(executing batch ...);
executor.execute();
}
我认为 TestExecutor
类应该实现Callable
并继续朝那个方向。
但是我想要能够做的是stop executor.execute()
如果耗时过长。
建议...?
$ b
EDIT
收到的许多建议假定执行的需要很长时间的方法包含一些并且可以周期性地检查变量。
然而,不是这样的。
您应该采取措施看看这些类:
,,
以下是一个示例:
public class TimeoutExample {
public static Object myMethod(){
//做你的事情,花费很长时间来执行
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 {
//确定,最多等待30秒
对象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);
}
}
}
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.
I'm using Java.
to illustrate:
logger.info("sequentially executing all batches...");
for (TestExecutor executor : builder.getExecutors()) {
logger.info("executing batch...");
executor.execute();
}
I figure the TestExecutor
class should implement Callable
and continue in that direction.
But all i want to be able to do is stop executor.execute()
if it's taking too long.
Suggestions...?
EDIT
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.
You should take a look at these classes :FutureTask, Callable, Executors
Here is an example :
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");
}
}
}
这篇关于如何封装一个方法,如果超过指定的超时,我可以终止它的执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!