spring quartz定时器的简单配置和使用
第一步:在MyEclipse下建立一个项目Spring_Clock,导入相关jar包spring.jar commons-collections.jar
commons-lang.jar commons-logging.jar quartz.jar
?
第二步: 新建立一个业务bean-->cn.yulon.service.MessageService
package cn.yulon.service;public class MessageService {int i;public void printLog(){i++;System.out.println("this is my timer:" +i);}}
?
?
第三步:在Spring配置文件time-bean.xml,如下
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"><beans><!-- 第一步: 配置好要定时调用的业务类 --><bean id="msgService" /><!-- 第二步: 定义好具体要使用类的哪一个业务方法 --><bean id="workDetail" ref="msgService"/> <!-- 要执行目标bean的哪一个业务方法 --> <property name="targetMethod" value="printLog"/> <!-- 是否并发 --> <property name="concurrent" value="false"/></bean><!-- 第三步: 定义好调用模式: 如每隔1秒钟调用一次或每天的哪个时间调用一次等 --><bean id="msgTrigger" ref="workDetail"/> <property name="cronExpression" value="0/1 * * * * ?"/></bean><!--第四步 把定义好的任务放到调度(Scheduler)工厂里面,注意这里的ref bean --> <bean value="0/1 * * * * ?"/>表示每隔一秒钟执行一次,例子如下:0 0 10,14,16 * * ? 每天上午10点,下午2点和下午4点 0 0,15,30,45 * 1-10 * ? 每月前10天每隔15分钟 30 0 0 1 1 ? 2012 在2012年1月1日午夜过30秒时 0 0 8-5 ? * MON-FRI 每个工作日的工作时间 - 区间 * 通配符 ? 你不想设置那个字段?
第四步:新建测试类SpringTest
public class SpringTest { public static void main(String[] args) { ApplicationContext act = new ClassPathXmlApplicationContext("time-bean.xml"); }?
运行结果如下 :this is my timer:1this is my timer:2this is my timer:3this is my timer:4this is my timer:5?
应用场合: 如做一些定时提醒,日志定时备份等应用