如何解决Springboot定时任务遇到的问题

  介绍

这篇文章给大家分享的是有关如何解决Springboot定时任务遇到的问题的内容。小编觉得挺实用的,因此分享给大家做个参考。一起跟随小编过来看看吧。

前言:在使用Springboot整合定时任务,发现当某个定时任务执行出现执行时间过长的情况时会阻塞其他定时任务的执行。

问题定位

后续通过翻查Springboot的文档以及打印日志(输出当前线程信息)得知问题是由于Springboot默认使用只要1个线程处理定时任务。

问题复盘

需要注意示例的Springboot版本为2.1.3。释放。

关键pom文件配置

& lt; !——继承父项目——比;   & lt; parent>   & lt; groupId> org.springframework.boot   & lt; artifactId> spring-boot-starter-parent   & lt; version> 2.1.3.RELEASE   & lt; relativePath/比;& lt; !——从库中查找父——比;   & lt;/parent>      …省略非关键配置      & lt; !——引入依赖——比;   & lt; dependencies>   & lt; dependency>   & lt; groupId> org.springframework.boot   & lt; artifactId> spring-boot-starter   & lt;/dependency>      & lt; dependency>   & lt; groupId> org.springframework.boot   & lt; artifactId> spring-boot-starter-test   & lt; scope> test   & lt;/dependency>   & lt;/dependencies>

定时任务

进口org.slf4j.Logger;   进口org.slf4j.LoggerFactory;   进口org.springframework.scheduling.annotation.Scheduled;   进口org.springframework.stereotype.Component;/* *   *定时任务   * @author RJH   *创建于2019-03-29   */@ component   公开课SimpleTask {      私有静态日志记录器=LoggerFactory.getLogger (SimpleTask.class);/* *   *执行会超时的任务,定时任务间隔为5000 ms(等价于5 s)   */@Scheduled (fixedRate=5000)   公共空间overtimeTask () {   尝试{   logger.info(“当前由overtimeTask");//休眠时间为执行间隔的2倍   thread . sleep (10000);   }捕捉(InterruptedException e) {   e.printStackTrace ();   }   }/* *   *正常的定时任务   */@Scheduled (fixedRate=5000)   公共空间simpleTask () {   logger.info(“当前由simpleTask");   }   }

启动类

进口org.springframework.boot.SpringApplication;   进口org.springframework.boot.autoconfigure.SpringBootApplication;   进口org.springframework.scheduling.annotation.EnableScheduling;      @SpringBootApplication   @EnableScheduling   公开课TaskDemoApplication {      公共静态void main (String [] args) {   SpringApplication.run (TaskDemoApplication.class, args);   }      }

运行结果

…省略非关键信息   59731 - - - 2019-03-29 21:22:38.410信息安排一com.rjh.task。当前由SimpleTask SimpleTask:   59731 - - - 2019-03-29 21:22:38.413信息安排一com.rjh.task。当前由overtimeTask SimpleTask:   59731 - - - 2019-03-29 21:22:48.413信息安排一com.rjh.task。当前由SimpleTask SimpleTask:   59731 - - - 2019-03-29 21:22:48.414信息安排一com.rjh.task。当前由overtimeTask SimpleTask:   59731 - - - 2019-03-29 21:22:58.418信息安排一com.rjh.task。当前由SimpleTask SimpleTask:   59731 - - - 2019-03-29 21:22:58.418信息安排一com.rjh.task。当前由overtimeTask SimpleTask:   59731 - - - 2019-03-29 21:23:08.424信息安排一com.rjh.task。当前由SimpleTask SimpleTask:   59731 - - - 2019-03-29 21:23:08.424信息安排一com.rjh.task。当前由overtimeTask SimpleTask:   59731 - - - 2019-03-29 21:23:18.425信息安排一com.rjh.task。当前由SimpleTask SimpleTask:   59731 - - - 2019-03-29 21:23:18.426信息安排一com.rjh.task。当前由overtimeTask SimpleTask:   …

结果分析

由运行结果可以看出:

    <李>每次定时任务的运行都是由<代码>安排一这个线程处理李 <李>正常运行的<代码> simpleTask> overtimeTask 阻塞导致了运行间隔变成了<代码> 10秒李

后面通过查阅<代码> Springboot>

解决方案

由于使用的<代码> Springboot> 2.1.3。释放>

使用Springboot配置

在配置文件中可以配置定时任务可用的线程数:

# #配置可用线程数为10   spring.task.scheduling.pool。大?10

如何解决Springboot定时任务遇到的问题