I have a Spring scheduled task defined in context.xml file which run every minute. the task calls a postgres stored procedure. The Stored procedure run time can last more than a minute. Will the spring framework call the same scheduler if the current run did not finish ? Thanks,
2
votes
1 Answers
2
votes
In spring framework,one scheduled task only executed by one thread,if the execute time longer than the interval period,the task will be delayed。Here is a simple example:
@Scheduled(cron = "0/3 * * * * *")
public void work() {
log.info("begin to do some work,current thread is {}", Thread.currentThread().getName());
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
log.error(e.toString());
}
}
I create a scheduled task,expected execution sequence: 0 3 6 9 ...,but the task need more time,so the execution sequence:0 6 12 18 ...
In spring all task will be executed by on thread(default),in order to reduce interference between tasks,we can support a thread pool to execute shceduled tasks like this:
@Bean
public ThreadPoolTaskScheduler taskExecutor() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(20);
return scheduler;
}
Other question about scheduled task in spring:Does spring @Scheduled annotated methods runs on different threads?