quartz有几种执行任务的方式,至于几种我也不知道,至少有两种吧:
一种是org.springframework.scheduling.quartz.CronTriggerBean方式,配置指定的时间执行一次任务,如<value>0 */30 * * * ?</value>就是30分钟执行一次;
一种是org.springframework.scheduling.quartz.SimpleTriggerBean方式,配置间隔多长时间执行一次任务,如<property name="repeatInterval" value="3000" />就是指定3秒执行一次任务;
二者是有区别的,CronTriggerBean可以指定在某个点执行任务,而SimpleTriggerBean似乎是做不到的,譬如你指定每天的凌晨23:59:59秒执行任务,只能用CronTriggerBean了。
现在如果你想项目启动的时候就执行任务,后面就按照指定的时间执行任务的话,就需要二者配合使用了。
我的项目是springmvc框架,在web.xml中做如下配置:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:conf/spring-common.xml,
classpath:conf/spring-config.xml,
classpath:conf/quartz-config.xml<!--看这里-->
</param-value>
</context-param>
然后在
quartz-config.xml中做如下配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
default-lazy-init="false">
<bean id="quartzJob" class="xx.xx.xx.QuartzJob" />
<!-- 5分钟更新 -->
<bean id="rsh_jobDetail_1"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject">
<ref bean="quartzJob" />
</property>
<property name="targetMethod">
<value>xxxxxx(你在QuartzJob中的方法)</value>
</property>
</bean>
<bean id="rsh_cronTrigger_1" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="rsh_jobDetail_1" />
<property name="cronExpression">
<value>0 */5 * * * ?</value>
</property>
</bean>
<!-- 配置项目启动后任务就执行一次 -->
<bean id="rsh_simpleTrigger1" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
<property name="jobDetail" ref="rsh_jobDetail_1" />
<property name="startDelay" value="500" />
<property name="repeatInterval" value="0" />
<property name="repeatCount" value="0" />
</bean>
<span style="white-space:pre"> </span><!--这里是关键,如果没有你的任务就执行不了了,哈哈哈哈-->
<bean id="startQuertz" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="rsh_simpleTrigger1" />
<ref bean="rsh_cronTrigger_1" />
</list>
</property>
</bean>
</beans>