如何使用 ThreadPoolTaskExecutor 设置任务超时 [英] How to set timeout for task using ThreadPoolTaskExecutor
问题描述
使用 ThreadPoolTaskExecutor
时是否可以使任务超时?我无法将 ThreadPoolTaskExecutor
更改为 ThreadPoolExecutor
或 ExecutorService
.
Is it possible to timeout a task when using ThreadPoolTaskExecutor
? I cannot change the ThreadPoolTaskExecutor
to ThreadPoolExecutor
or to ExecutorService
.
推荐答案
在向您的 ThreadPoolTaskExecutor
提交 Callable
后,您应该得到一个 Future
.而在这个Future
上,你可以用一个TimeUnit
调用get(long timeout, TimeUnit unit)
函数,也就是超时,最大程序将通过抛出 TimeoutException
等待直到未来交付或继续进行的时间.
After submitting a Callable
to your ThreadPoolTaskExecutor
you should get a Future
. And on this Future
, you can call the get(long timeout, TimeUnit unit)
function with a TimeUnit
, which is the timeout, the maximum time the program will wait until either the future delivers or moves on, by throwing a TimeoutException
.
即(未经证实的伪代码)
ie (unconfirmed pseudocode)
Future myFuture = threadPoolTaskExecutor.submit(myCallable);
try {
myResult = myFuture.get(5l,TimeUnit.SECONDS);
} catch(TimeoutException e) {
// Timeout-Related stuff here
}
这篇关于如何使用 ThreadPoolTaskExecutor 设置任务超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!