首先你需要定义一个bean类,和需要执行的方法(需要引入quartz-1.8.6.jar和org.springframework.context.support-3.0.2.RELEASE.jar)
public class QuartzTask {
public void doSimpleTriggerTask() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("doing simpleTrigger task..." + sdf.format(new Date()));
}
public void doCronTriggerTask() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("doing cronTrigger task..." + sdf.format(new Date()));
}
}
然后在spring配置文件中配置
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="quartzTask" class="cn.itcast.nsfw.complain.QuartzTask"></bean>
<bean id="jobDetail1" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="quartzTask"></property>
<property name="targetMethod" value="doSimpleTriggerTask"></property>
<property name="concurrent" value="false"></property>
</bean>
<bean id="jobDetail2" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="quartzTask"></property>
<property name="targetMethod" value="doCronTriggerTask"></property>
<property name="concurrent" value="false"></property>
</bean>
<bean id="simplerTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
<property name="jobDetail" ref="jobDetail1"></property>
<property name="startDelay" value="2000"></property>
<property name="repeatInterval" value="2000"></property>
</bean>
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="jobDetail2"></property>
<property name="cronExpression" value="* * * 18c * ?"></property>
</bean>
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="cronTrigger"/>
</list>
</property>
</bean>
</beans>