ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(1);
scheduler.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("A is running");
}
}, 10, 5, TimeUnit.SECONDS);
Thread.sleep(20000);
scheduler.shutdown();
if (scheduler.getCompletedTaskCount() > 0) {
System.out.println("A is done.");
}
How verify a ScheduledExecutorService has started?
-
29-07-2022 - |
Question
Description
A task A is running, that can last from 2s to 60+s.
While A is running, I scheduled a ExecutorService that after 10s (delay), would print "running" every 5s (fixed rate).
ScheduledExecutorService scheduleNotifications = Executors
.newSingleThreadScheduledExecutor();
scheduleNotifications.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("A is running");
}
}, 10, 5, TimeUnit.SECONDS);
Once A is done, I wish to print "A is done." but only if my ScheduledExecutorService task has started, meaning it printed "running" at least once.
- If A finished before 10s, I do not print anything.
- If A takes more than 10s, I print "running" every 5s and then "done" once A is finished.
How could I do that without using a boolean flag inside the schduled runnable
. Is there a way to check that my service started?
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow