一 springMVC自带task启动后加载 上代码
首先添加依赖引入task
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
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-4.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="com.demo.controller" />//开启扫描任务类
<task:executor id="executor" pool-size="5" />
<task:scheduler id="scheduler" pool-size="10" /> //配置调度和注解调度
<task:annotation-driven executor="executor" scheduler="scheduler" />//开启定时任务
</beans>
是的 这就完成了 就折磨简单
测试类:
@Component
public class ToTimer {
/**@Scheduled(cron = "0 10 11 ? * *")
* 每天11点10启动任务
* @Scheduled(cron = "0/5 * * * * ?")//每隔5秒隔行一次
*/
@Scheduled(cron = "0 10 11 ? * *")
public void test1()
{
System.out.println("job1 开始执行..."+new Date());
}
}
第二种 spring封装的Quartz
首先 pom中
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.2.4</version>
</dependency>
其次 spring xml文件中
<!-- 定义一个任务类 -->
<bean id="myJob" class="com.zntz.web.job.myjob"></bean>
<!-- jobDetail -->
<bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="myJob"></property>
<property name="targetMethod" value="execute"></property>
<property name="concurrent" value="false" /><!-- 作业不并发调度 -->
</bean>
<!-- 定义trigger 触发器 -->
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="jobDetail"></property>
<property name="cronExpression" value="0/10 * * * * ?"></property>
</bean>
<!-- 定义scheduler调度器 -->
<bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="cronTrigger"/>
</list>
</property>
</bean>