问题
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?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/4814916/checking-if-periodic-scheduledfuture-is-running-now