Spring Boot Schedule任务没有等待完成即可关闭

时间:2019-07-08 04:49:25

标签: java spring-boot scheduled-tasks

我有一个执行以下任务的计划任务:

@Configuration
@EnableScheduling
public class SchedulerConfig {
@Value("${scheduled.task.pool.size}")
private int schedulerPoolSize;

@Value("${scheduled.task.thread.name.prefix}")
private String threadNamePrefix;

@Bean
ThreadPoolTaskScheduler taskScheduler(){
    ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler() {
        @Override
        public void destroy() {
            this.getScheduledThreadPoolExecutor().setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
            super.destroy();
        }
    };

    threadPoolTaskScheduler.setPoolSize(schedulerPoolSize);
    threadPoolTaskScheduler.setThreadNamePrefix(threadNamePrefix);               
    threadPoolTaskScheduler.setWaitForTasksToCompleteOnShutdown(true);
    threadPoolTaskScheduler.setAwaitTerminationSeconds(20);
    return threadPoolTaskScheduler;
}

这是我的任务

@Scheduled(fixedDelayString = "${scheduled.task.job1.fixed.delay}") 
public void scheduleTaskJob1() {
    logger.info("Fixed delay task called every 3 seconds after latest finished Execution Time - {}",
            dateTimeFormatter.format(LocalDateTime.now()));
    String HttpErrorCode = "xxx";
    try {
            //10s taken to complete
        HttpErrorCode = mappingErrorService.getHttpErrorCode();

    } catch (Exception ex) {
        logger.error("Ran into an error {}", ex);
    }

    logger.info("Current Thread : {} " + HttpErrorCode, Thread.currentThread().getName());
}

我已经测试了很多次,但是当停止我的应用程序时,它总是显示Ran出现错误...而我的任务没有成功完成。 似乎setWaitForTasksToCompleteOnShutdown和setAwaitTerminationSeconds无法正常工作。

我也尝试

spring.quartz.wait-for-jobs-to-complete-on-shutdown=true 

但是没有运气。我的任务总是异常,没有得到结果

0 个答案:

没有答案