Maven配置
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.2</version>
</dependency>
applicationContext-schedule.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.0.xsd
">
<!-- 自动扫描来加载 -->
<task:annotation-driven />
</beans>
TestTask.java
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class TestTask {
int i=0;
@Scheduled(cron = "0/5 * * * * ?")
public void testT1(){
i++;
System.out.println("任务1执行"+i);
}
@Scheduled(cron = "0/5 * * * * ?")
public void testT2(){
i++;
System.out.println("任务2执行"+i);
}
}
上面设置了两个5秒执行一次的定时任务,Spring通过@Component与@Scheduled两个注解来判断定时任务。
但是,使用上面方式配置,虽然任务可以正常运行,但是在启动的时候会显示
2016-04-19 14:00:37.281 [main] DEBUG o.s.s.a.ScheduledAnnotationBeanPostProcessor -Could not find default ScheduledExecutorService bean
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.scheduling.TaskScheduler] is defined
在网上搜索资料后,总结出ScheduledAnnotationBeanPostProcessor会首先尝试得到一个TaskScheduler,ScheduledExecutorService,然后它继续执行任务。但是我们没有给它配置相关的属性,所以我们可以在配置的时候做如下调整
<!-- executor线程池,含义和java.util.concurrent.Executor是一样的,pool-size的大小官方推荐为5~10 -->
<task:executor id="executor" pool-size="5" />
<!-- scheduler的pool-size是ScheduledExecutorService线程池,默认为1 -->
<task:scheduler id="scheduler" pool-size="5" />
<task:annotation-driven executor="executor"
scheduler="scheduler" />