I need some kind of service that will run a few tasks simultaneously and in an interval of 1 second for 1 minute.
If one of the tasks fails, I want to stop the service and every task that ran with it with some kind of indicator that something went wrong, otherwise if after one minute everything went well the service will stop with an indicator that all went well.
For example,i have 2 functions:
Runnable task1 = ()->{
int num = Math.rand(1,100);
if (num < 5){
throw new Exception("something went wrong with this task,terminate");
}
}
Runnable task2 = ()->{
int num = Math.rand(1,100)
return num < 50;
}
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
task1schedule = scheduledExecutorService.scheduleAtFixedRate(task1, 1, 60, TimeUnit.SECONDS);
task2schedule = scheduledExecutorService.scheduleAtFixedRate(task2, 1, 60, TimeUnit.SECONDS);
if (!task1schedule || !task2schedule) scheduledExecutorService.shutdown();
Any ideas on how should I tackle this and make things as generic as possible?
Math.rand
isn't a built-in API. An implementation ofRunnable
must have avoid run
definition. Type oftask1/2schedule
would beScheduledFuture<?>
in the provided context. Moving to the actual question, how does it go around to make use ofawaitTermination
? You could do that asscheduledExecutorService.awaitTermination(1,TimeUnit.MINUTES);
. Alternatively, what about checking if any of the tasks got canceled before its normal completion:if (task1schedule.isCancelled() || task2schedule.isCancelled()) scheduledExecutorService.shutdown();
? – Incur