---
title: "在OpenJWeb平台中使用Spring框架配置定时器的实例"
author: "cjc"
date: "2008-03-16T11:15:00Z"
tags: []
slug: "openjweb-spring"
draft: false
lastmod: "2008-03-16T11:15:00Z"
id: 446899
url: "https://cjc.iteye.com/blog/446899"
---

由于OpenJWeb平台集成了Spring框架,所以定时作业的开发非常方便,首先一个被定时器调用的类:

package org.openjweb.common.timer;

import org.apache.log4j.Logger;  
import org.quartz.JobExecutionContext;  
import org.quartz.JobExecutionException;  
import org.springframework.scheduling.quartz.QuartzJobBean;

public class JobSchedule extends QuartzJobBean  
{  
static Logger logger = Logger.getLogger(JobSchedule.class);  
static long counter = 0; //计数器  
public synchronized void doTimerSchedule()  
{  
System.out.println("测试定时器........");  
}

protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {  
// TODO Auto-generated method stub

}

}

上面的doTimerSchedule是被定时调用的方法,下文讲述此方法在spring配置文件中如何配置为定时调用:

&lt;?xml version="1.0" encoding="GB2312"?&gt;  
&lt;beans xmlns="[http://www.springframework.org/schema/beans](http://www.springframework.org/schema/beans)"  
xmlns:xsi="[http://www.w3.org/2001/XMLSchema-instance](http://www.w3.org/2001/XMLSchema-instance)"  
xsi:schemaLocation="[http://www.springframework.org/schema/beans](http://www.springframework.org/schema/beans)  
[http://www.springframework.org/schema/beans/spring-beans-2.0.xsd](http://www.springframework.org/schema/beans/spring-beans-2.0.xsd)"&gt;

&lt;!-- Timer Schedule config start --&gt;  
&lt;!-- defime a business timer object--&gt;  
&lt;bean id="EAITimerBean" class="org.openjweb.common.timer.JobSchedule"/&gt;  
&lt;!--defime which method of class to be called in timer schedule --&gt;  
&lt;bean id="EAITimerMethod" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"&gt;  
&lt;property name="targetObject" ref="EAITimerBean" /&gt;  
&lt;property name="targetMethod" value="doTimerSchedule" /&gt;  
&lt;property name="concurrent" value="false" /&gt; &lt;!--将并发设置为false--&gt;  
&lt;/bean&gt;  
&lt;!-- 设置定时器 --&gt;  
&lt;bean id="eaiTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"&gt;  
&lt;property name="jobDetail" ref="EAITimerMethod" /&gt;  
&lt;!--每两分钟触发--&gt;  
&lt;property name="cronExpression" value="0 1/2 * * * ?" /&gt;  
&lt;/bean&gt;

&lt;bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"&gt;  
&lt;property name="triggers"&gt;  
&lt;list&gt;  
&lt;!--EAI调度器,list下可加入其他的调度器--&gt;  
&lt;ref bean="eaiTrigger"/&gt;  
&lt;/list&gt;  
&lt;/property&gt;  
&lt;/bean&gt;

&lt;!-- Timer Schedule config end --&gt;

&lt;/beans&gt;

如果你的开发环境中集成了spring后,将上面的代码和xml配置放到你自己应用对应的位置编译启动tomcat后可以看到后台每两分钟输出一次调试信息.1/2表示每两分钟的第一分钟.