USer22999299
USer22999299

Reputation: 5674

How to set timeout for task using ThreadPoolTaskExecutor

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

Upvotes: 5

Views: 6193

Answers (2)

vivek21563
vivek21563

Reputation: 21

Refer my below Git hub link for TimeOutThreadPoolTaskExecutor

https://github.com/vivek-gupta-21563/timeoutthreadpool

you can execute or submit a task with preferred time out parameters

execute(() -> System.out.println("Task to execute"), 2, TimeUnit.Minute);

submit(() -> System.out.println("Task to execute"), 2, TimeUnit.Minute);

Upvotes: 2

Scorpio
Scorpio

Reputation: 2327

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
}

Upvotes: 8

Related Questions