I用於在超時後中斷任務的ExecutorService。我爲此使用ScheduledExecutorService。首先,我提交了該線程,並立即開始並保留創建的未來。之後,我使用ScheduledExecutorService作爲一項新任務,在一段時間後取消保留的未來。ScheduledExecutorService和ThreadPoolTaskExecutor在超時後中斷任務
//Start Spring executor to submit tasks
ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor) ApplicationContextProvider.getApplicationContext().getBean("taskExecutor");
CompletionService completionService = new ExecutorCompletionService(taskExecutor);
//End Spring executor to submit tasks
// Start ScheduledExecutorService to submit returned future object to timeout
ScheduledExecutorService executor = Executors.newScheduledThreadPool(Integer.parseInt(config.getProperty("DBPOLLER_COREPOOLSIZE")));
final Future<String> future = completionService.submit(batchJob); // Submit actual task and get future
// submit future
executor.schedule(new Runnable() {
public void run() {
future.cancel(true);
}
}, dbPollerTimeOut, TimeUnit.MINUTES);
int count = taskExecutor.getActiveCount();
if (count == 0) {
taskExecutor.shutdown();
executor.shutdown();
finalExitStatus = 0;
break;
}
我已經實現瞭解決方案,它是在以下網址: ExecutorService that interrupts tasks after a timeout,它做工精細,直到超時,但一旦發生超時,這將取消所有enter code here
任務我線程池是不能接受的。我只需要取消長時間運行並超時的任務。
任何想法如何實現這一目標?
什麼是'batchJob'?取消它必須負責取消「所有'在這裏輸入代碼'任務[in] ThreadPool」。所以,顯示'batchJob'的代碼。 'batchJob'是否參考了很多其他任務?這將是一個問題。 – erickson
請參閱[輸入鏈接說明](http://stackoverflow.com/questions/42946627/scheduledexecutorservice-that-interrupts-after-a-timeout) –