@Scheduled解决单线程问题

在SSM项目中,当使用@Scheduled注解执行长时间任务时,系统其他功能会受到影响,因为默认是单线程执行。为了解决这个问题,可以通过配置XML文件启用定时任务的多线程执行。在spring.xml中添加了task调度器配置,创建了一个包含5个线程的线程池,使得多个定时任务能并发执行。测试代码展示了两个定时任务testtask1和testtask2如何按照设定的时间间隔并发运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在ssm项目中使用这个注解的时候 当和我开启一个定时任务去执行一个需要运行很长时间的程序时 发现系统中其他功能不能同时执行 查阅资料发现 使用了@Scheduled这个注解就默认为单线程执行 其他线程需要等待这个线程的结束 解决这个问题的方法 可以为该注解配置xml文件 让其线程改为多线程 我的xml配置文件放在了spring.xml中 代码如下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:task="http://www.springframework.org/schema/task" 

    xsi:schemaLocation="     
          http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context.xsd
          http://www.springframework.org/schema/task
          http://www.springframework.org/schema/task/spring-task.xsd"
          default-autowire="byName" default-lazy-init="false">

    <!-- 1.扫描指定的包 包名改为自己的包名 -->
    <context:component-scan base-package="com.qa_qc.gmp.ssm.schedule.attendance"/>

    <!-- 2.启用定时任务  “myTask不用改  只需要和下面的保持一致就行”-->
    <!-- <task:annotation-driven /> -->
    <task:annotation-driven scheduler="myTask" />

    <!-- 3.配置定时任务的线程池 -->
    <task:scheduler id="myTask" pool-size="5"/>
</beans>

测试代码

    @Scheduled(cron="0/20 * * * * ?") 
    public  void testtask1(){
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"---现在执行线程2,每20秒执行一次:");
    }

    @Scheduled(cron="0/15 * * * * ?") 
    public  void testtask2(){
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"---现在执行线程1,每15秒执行一次:");
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

测试结果

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值