Reputation: 8609
I have a periodic task scheduled via Spring TaskScheduler.schedule(Runnable, Trigger)
.
Given the returned ScheduledFuture
, is there any way to check, if the task is running at current moment?
Upvotes: 3
Views: 6582
Reputation: 158
If you need to check non-periodic future (java.util.concurrent.FutureTask) the solution with only
future.getDelay(TimeUnit.MILLISECONDS) <= 0
doesn't work. You can't even combine
future.getDelay(TimeUnit.MILLISECONDS) <= 0 && !future.isDone()
because future.isDone()
returns true for all states except NEW which means "Scheduled". But if future is just started future.getDelay(TimeUnit.MILLISECONDS) <= 0 && !future.isDone()
never return true because not started future (NEW) never has negative delay
So I came up with pretty stupid simple solution and it works
future.isDone() && future.toString().startsWith("[Not completed]")
It's a bit ugly but does the job
Upvotes: 0
Reputation: 8609
After a bit of testing,
public static boolean isRunning(ScheduledFuture future) {
return future.getDelay(TimeUnit.MILLISECONDS) <= 0;
}
works like a charm. Seems the task gets rescheduled only after completion, so getDelay()
returns negative value.
Upvotes: 8
Reputation: 16060
You can change you Runnable like this:
class Runner implements Runnable{
public volatile boolean RUNNING = false;
public void run(){
RUNNING = true;
try{
// Your code
} finally {
RUNNING = false;
}
}
}
edit
Thought operations with boolean
are atomic and don't need to be volatile.
Upvotes: 2