定时任务一般分为两种:
1.每隔指定时间则触发一次,在Quartz中对应的触发器为:org.springframework.scheduling.quartz.SimpleTriggerBean
2.每到指定时间则触发一次,在Quartz中对应的调度器为:org.springframework.scheduling.quartz.CronTriggerBea
算了不讲这些没用的概念了,直接上代码。你敲一遍就会了,遇到报错的你也就理解原理了。
写一个你需要定时执行的方法
例如:
package com.quartz.service;
public class EarnMoney {
private int num=0;
public void earn(){
System.out.println("我赚了"+(num++)+"万块钱");
}
}
3.写spring-quartz.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:mvc="http://www.springframework.org/schema/mvc"
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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- service bean-->
<bean id = "addService" class="com.quartz.service.EarnMoney">
</bean>
<!-- 任务 bean-->
<bean id="myjob" class="org.springframework.scheduling.quartz.JobDetailBean">
<!--指定任务类 -->
<property name="jobClass" value="com.quartz.test.TestQuartz"></property>
<!--为任务bean注入属性 -->
<property name="jobDataMap">
<map>
<entry key="add" value-ref="addService"></entry>
</map>
</property>
</bean>
<!-- 任务触发器 -->
<bean id="myTriggers" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="myjob"></property>
<property name="cronExpression" value="0/2 * * * * ?"></property>
</bean>
<!-- 任务调度工厂-->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="myTriggers"/>
</list>
</property>
</bean>
</beans>
4.把spring-quartz.xml放到web.xml中执行
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-quartz.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>