如何使用 ThreadPoolTask​​Executor 设置任务超时 [英] How to set timeout for task using ThreadPoolTaskExecutor

查看:712
本文介绍了如何使用 ThreadPoolTask​​Executor 设置任务超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 ThreadPoolTask​​Executor 时是否可以使任务超时?我无法将 ThreadPoolTask​​Executor 更改为 ThreadPoolExecutorExecutorService.

Is it possible to timeout a task when using ThreadPoolTaskExecutor? I cannot change the ThreadPoolTaskExecutor to ThreadPoolExecutor or to ExecutorService.

推荐答案

在向您的 ThreadPoolTask​​Executor 提交 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
}

这篇关于如何使用 ThreadPoolTask​​Executor 设置任务超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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