搜索
首页Javajava教程Springboot定时任务遇到的问题解决

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

Mar 30, 2019 am 10:32 AM
javaspring定时任务线程池

本篇文章给大家带来的内容是关于Springboot定时任务遇到的问题解决,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

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

问题定位

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

问题复盘

需要注意示例的Springboot版本为2.1.3.RELEASE。

关键pom文件配置

    <!--继承父项目-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    
    ...省略非关键配置
    
    <!-- 引入依赖-->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

定时任务

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 定时任务
 * @author RJH
 * create at 2019-03-29
 */
@Component
public class SimpleTask {

    private static Logger logger= LoggerFactory.getLogger(SimpleTask.class);

    /**
     * 执行会超时的任务,定时任务间隔为5000ms(等价于5s)
     */
    @Scheduled(fixedRate = 5000)
    public void overtimeTask(){
        try {
            logger.info("current run by overtimeTask");
            //休眠时间为执行间隔的2倍
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 正常的定时任务
     */
    @Scheduled(fixedRate = 5000)
    public void simpleTask(){
        logger.info("current run by simpleTask");
    }
}

启动类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class TaskDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(TaskDemoApplication.class, args);
    }

}

运行结果

...省略非关键信息
2019-03-29 21:22:38.410  INFO 59731 --- [   scheduling-1] com.rjh.task.SimpleTask                  : current run by simpleTask
2019-03-29 21:22:38.413  INFO 59731 --- [   scheduling-1] com.rjh.task.SimpleTask                  : current run by overtimeTask
2019-03-29 21:22:48.413  INFO 59731 --- [   scheduling-1] com.rjh.task.SimpleTask                  : current run by simpleTask
2019-03-29 21:22:48.414  INFO 59731 --- [   scheduling-1] com.rjh.task.SimpleTask                  : current run by overtimeTask
2019-03-29 21:22:58.418  INFO 59731 --- [   scheduling-1] com.rjh.task.SimpleTask                  : current run by simpleTask
2019-03-29 21:22:58.418  INFO 59731 --- [   scheduling-1] com.rjh.task.SimpleTask                  : current run by overtimeTask
2019-03-29 21:23:08.424  INFO 59731 --- [   scheduling-1] com.rjh.task.SimpleTask                  : current run by simpleTask
2019-03-29 21:23:08.424  INFO 59731 --- [   scheduling-1] com.rjh.task.SimpleTask                  : current run by overtimeTask
2019-03-29 21:23:18.425  INFO 59731 --- [   scheduling-1] com.rjh.task.SimpleTask                  : current run by simpleTask
2019-03-29 21:23:18.426  INFO 59731 --- [   scheduling-1] com.rjh.task.SimpleTask                  : current run by overtimeTask
...

结果分析

由运行结果可以看出:

  1. 每次定时任务的运行都是由scheduling-1这个线程处理
  2. 正常运行的simpleTaskovertimeTask阻塞导致了运行间隔变成了10

后面通过查阅Springboot的文档也得知了定时任务默认最大运行线程数为1

解决方案

由于使用的Springboot版本为2.1.3.RELEASE,所以有两种方法解决这个问题

使用Springboot配置

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

## 配置可用线程数为10
spring.task.scheduling.pool.size=10

自定义定时任务的线程池

使用自定义的线程池代替默认的线程池

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

/**
 * 定时任务配置类
 * @author RJH
 * create at 2019-03-29
 */
@Configuration
public class ScheduleConfig {

    /**
     * 此处方法名为Bean的名字,方法名无需固定
     * 因为是按TaskScheduler接口自动注入
     * @return
     */
    @Bean
    public TaskScheduler taskScheduler(){
        // Spring提供的定时任务线程池类
        ThreadPoolTaskScheduler taskScheduler=new ThreadPoolTaskScheduler();
        //设定最大可用的线程数目
        taskScheduler.setPoolSize(10);
        return taskScheduler;
    }
}

本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注PHP中文网的Java视频教程栏目!

以上是Springboot定时任务遇到的问题解决的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:segmentfault。如有侵权,请联系admin@php.cn删除
Java平台是否独立,如果如何?Java平台是否独立,如果如何?May 09, 2025 am 12:11 AM

Java是平台独立的,因为其"一次编写,到处运行"的设计理念,依赖于Java虚拟机(JVM)和字节码。1)Java代码编译成字节码,由JVM解释或即时编译在本地运行。2)需要注意库依赖、性能差异和环境配置。3)使用标准库、跨平台测试和版本管理是确保平台独立性的最佳实践。

关于Java平台独立性的真相:真的那么简单吗?关于Java平台独立性的真相:真的那么简单吗?May 09, 2025 am 12:10 AM

Java'splatFormIndenceIsnotsimple; itinvolvesComplexities.1)jvmCompatiblemustbeiblemustbeensurecensuredAcrospPlatForms.2)nativelibrariesandsycallsneedcarefulhandling.3)

Java平台独立性:Web应用程序的优势Java平台独立性:Web应用程序的优势May 09, 2025 am 12:08 AM

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

JVM解释:Java虚拟机的综合指南JVM解释:Java虚拟机的综合指南May 09, 2025 am 12:04 AM

thejvmistheruntimeenvorment forexecutingjavabytecode,Cocucialforjava的“ WriteOnce,RunanyWhere”能力

Java的主要功能:为什么它仍然是顶级编程语言Java的主要功能:为什么它仍然是顶级编程语言May 09, 2025 am 12:04 AM

JavaremainsatopchoicefordevelopersduetoitsplatFormentence,对象与方向设计,强度,自动化的MememoryManagement和ComprechensivestAndArdArdArdLibrary

Java平台独立性:这对开发人员意味着什么?Java平台独立性:这对开发人员意味着什么?May 08, 2025 am 12:27 AM

Java'splatFormIndependecemeansDeveloperScanWriteCeandeCeandOnanyDeviceWithouTrecompOlding.thisAcachivedThroughThroughTheroughThejavavirtualmachine(JVM),WhaterslatesbyTecodeDecodeOdeIntComenthendions,允许univerniverSaliversalComplatibilityAcrossplatss.allospplats.s.howevss.howev

如何为第一次使用设置JVM?如何为第一次使用设置JVM?May 08, 2025 am 12:21 AM

要设置JVM,需按以下步骤进行:1)下载并安装JDK,2)设置环境变量,3)验证安装,4)设置IDE,5)测试运行程序。设置JVM不仅仅是让其工作,还包括优化内存分配、垃圾收集、性能调优和错误处理,以确保最佳运行效果。

如何查看产品的Java平台独立性?如何查看产品的Java平台独立性?May 08, 2025 am 12:12 AM

toensurejavaplatFormIntence,lofterTheSeSteps:1)compileAndRunyOpplicationOnmultPlatFormSusiseDifferenToSandjvmversions.2)upureizeci/cdppipipelinelikeinkinslikejenkinsorgithikejenkinsorgithikejenkinsorgithikejenkinsorgithike forautomatecross-plateftestesteftestesting.3)

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。