stop Spring Scheduled execution if it hangs after some fixed time

后端 未结 3 1481
一个人的身影
一个人的身影 2020-12-10 12:16

I have used Spring Framework\'s Scheduled to schedule my job to run at every 5 mins using cron. But sometime my job waits infinitely for an external resource an

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-10 13:03

    I'm not sure this will work as expected. Indeed the keepAlive is for IDLE thread and I don't know if your thread waiting for resources is in IDLE. Furthermore it's only when the number of threads is greater than the core so you can't really know when it happen unless you monitor the threadpool.

    keepAliveTime - when the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating.

    What you can do is the following:

    public class MyTask {
    
        private final long timeout;
    
        public MyTask(long timeout) {
            this.timeout = timeout;
        }
    
        @Scheduled(cron = "")
        public void cronTask() {
            Future result = doSomething();
            result.get(timeout, TimeUnit.MILLISECONDS);
        }
    
        @Async
        Future doSomething() {
            //what i should do
            //get ressources etc...
        }
    }
    
    
    

    Don't forget to add @EnableAsync

    It's also possible to do the same without @Async by implementing a Callable.

    Edit: Keep in mind that it will wait until timeout but the thread running the task won't be interrupted. You will need to call Future.cancel when TimeoutException occurs. And in the task check for isInterrupted() to stop the processing. If you are calling an api be sure that isInterrupted() is checked.

    提交回复
    热议问题