Checking if periodic ScheduledFuture is running now

混江龙づ霸主 提交于 2019-12-23 19:18:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!