I have a program (thread) which starts a task on a remote machine on the cloud. I want to monitor the progress of this task and if it exceeds a specific timeout T, then it will be cancelled and more cloud resources will be added and the task will start again.
How can I monitor the thread which is executing this task?
Example Scenarios:
Timout = 1 hour, the task is finished in 40 mins, hence everything should terminate normally.
Timout = 1 hour, the task has failed after 55 mins due to lack of resources, hence more resources added and the task is started again
Timout = 1 hour, the task did not finish after 1 hour, hence its killed and more resources added then the task is started again.
So how can I implement that timely monitoring in java?
您正在寻找ScheduledThreadPoolExecutor
类,正是该类。
You could submit the task to an ExecutorService, try to get the result with a timeout and if you have a timeout, cancel the task.
It could look like:
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<?> future = executor.submit(yourTask);
try {
future.get(1, TimeUnit.HOURS);
} catch (TimeoutException e) {
future.cancel(true);
resubmitWithMoreResources();
} catch (ExecutionException e) {
Throwable underlyingCause = e.getCause();
if (underlyingCause instanceof ResourceException) {
resubmitWithMoreResources();
} else {...}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.