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" class="cn.yulon.service.MessageService" />
<!-- 第二步: 定义好具体要使用类的哪一个业务方法 -->
<bean id="workDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<!-- 目标bean -->
<property name="targetObject" ref="msgService"/>
<!-- 要执行目标bean的哪一个业务方法 -->
<property name="targetMethod" value="printLog"/>
<!-- 是否并发 -->
<property name="concurrent" value="false"/>
</bean>
<!-- 第三步: 定义好调用模式: 如每隔1秒钟调用一次或每天的哪个时间调用一次等 -->
<bean id="msgTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="workDetail"/>
<property name="cronExpression" value="0/1 * * * * ?"/>
</bean>
<!--第四步 把定义好的任务放到调度(Scheduler)工厂里面,注意这里的ref bean -->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="msgTrigger"/>
</list>
</property>
</bean>
</beans>

在xml里配置值得关注的是<property name="cronExpression" 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

Java代码
1.public class SpringTest {
2.
3. public static void main(String[] args) {
4.
5. ApplicationContext act = new ClassPathXmlApplicationContext("time-bean.xml");
6. }
public class SpringTest {

public static void main(String[] args) {

ApplicationContext act = new ClassPathXmlApplicationContext("time-bean.xml");
}


运行结果如下 :

Xml代码
1.this is my timer:1
2.this is my timer:2
3.this is my timer:3
4.this is my timer:4
5.this is my timer:5
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值