因Spring集成了QuartzJob,所以实现定时作业调度非常方便,首先实现一个作业调度类,类里面可以任意增加用于定时调用的方法,如定时发邮件,定时构造索引,工作流引擎定时监控等,下面是一个继承了的类:
import org.apache.log4j.Logger;
//import org.apache.lucene.demo.IndexHTML;
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()
{
counter++;
System.out.println("测试定时器,总计数:"+String.valueOf(counter));
}
protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
// TODO Auto-generated method stub
}
public synchronized void doBuildIndex()
{
System.out.println("开始构造索引库....");
//String indexPath = ServiceLocator.getSysConfigService().getStringValueByParmName("luceneIndexDir");
//String filePath = ServiceLocator.getSysConfigService().getStringValueByParmName("searchRoot");
//IndexHTML.buildIndex(indexPath,filePath);
System.out.println("索引库构造完毕!");
}
}
有了这个类以后,我们可以在spring的配置文件配置一个定时器,定时调用doTimerSchedule(),下面是spring配置文件的配置定时器的例子:
<!-- Timer schedule -->
<bean id="defaultTimerBean" class="org.openjweb.core.schedule.JobSchedule"/>
<bean id="defaultTimerMethod" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="defaultTimerBean" />
<property name="targetMethod" value="doTimerSchedule" />
<property name="concurrent" value="false" /> <!--将并发设置为false-->
</bean>
<bean id="defaultTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="defaultTimerMethod" />
<!--每三分钟的第一分钟触发-->
<property name="cronExpression" value="0 1/3 * * * ?" />
</bean>
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<!--作业调度器,list下可加入其他的调度器-->
<ref bean="defaultTrigger"/>
</list>
</property>
</bean>
如果还要配置另外的定时器定时执行doBuildIndex,则 增加下面的配置:
<bean id="luceneTimerMethod" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="defaultTimerBean" />
<property name="targetMethod" value="doBuildIndex" />
<property name="concurrent" value="false" /> <!--将并发设置为false-->
</bean>
<bean id="luceneTimerTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="luceneTimerMethod" />
<property name="cronExpression" value="0 1/30 * * * ?" /> <!--每30分钟构造一次索引-->
</bean>
并在上面的<ref bean="defaultTrigger"/>下面增加<ref bean="luceneTimerTrigger"/>.
不过奇怪的是,<property name="cronExpression" value="0 1/3 * * * ?" />
设置了每3分钟的第1分钟执行一次,但后台输出在每次时间到的时候定时器运行了两便,为什么?哪位高人知道原因指点一下?