在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();
}
}
测试结果
