Spring+quartz实现定时任务实例

来源:互联网 发布:每天读书 知乎 编辑:程序博客网 时间:2024/06/05 07:59

前面使用S2SH做了一个会员和员工管理的模块,里面涉及东西很少,作为自己使用SSH开发的一步,整合过程中,除了员工管理系统中几张表的关系外,没有其他难点。现在想

做一个网上商城的订单管理的模块,想到没有支付的订单都是有存放的时间的,过期就会自动删除订单,于是想到我们班一位大神使用quartz来定时抓取自己博客的页面内容,感觉quartz也可以过期来自动删除订单,于是就先做个实例来测试一下如何使用Spring+quartz来实现定时的效果。

首先是jar包:除了Spring的jar包外,我们还需要导入:quartz-all-1.6.0和spring-context-support-3.2.3.RELEASE.jar(这个也在spring里面只不过之前没有导入里面去)。

然后是写一个需要定时执行的方法:

public class Test{ public void work(){System.out.println("开始执行work"); }}
配置beans.xml:

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"><!-- 要调用的工作类 --><bean id="test" class="Test.Test"></bean><!-- 定义调用对象和调用对象的方法 --><bean id="jobtask"class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"><!-- 调用的类 --><property name="targetObject"><ref bean="test"/></property><!-- 调用类中的方法 --><property name="targetMethod"><value>work</value></property></bean><!-- 定义触发时间 --><bean id="doTime" class="org.springframework.scheduling.quartz.CronTriggerBean"><property name="jobDetail"><ref bean="jobtask"/></property><!-- cron表达式 --><property name="cronExpression"><value>0 * 08-21 * * ?</value>//8di</property></bean><!-- 总管理类 如果将lazy-init='false'那么容器启动就会执行调度程序 --><bean id="startQuertz" lazy-init="false" autowire="no"class="org.springframework.scheduling.quartz.SchedulerFactoryBean"><property name="triggers"><list><ref bean="doTime"/></list></property></bean></beans>

主函数:

System.out.println("主函数开始执行.");ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");//如果配置文件中将startQuertz bean的lazy-init设置为false 则不用实例化//context.getBean("startQuertz");System.out.print("主函数结束,等待定时任务执行.");