spring 定时服务调度quartz(一)

本文介绍了在项目中使用Quartz作为定时服务的场景,以及Spring如何支持Quartz。内容涉及Quartz的两种实现方式,包括实现QuartzJobBean以及通过Spring包装成quartzjobbean。配置触发器后,定时服务会在Spring配置文件加载时自动启动。

        在项目中有进可能会用到定进服务,一些简单的定时服务可以用java中的timer,timertask来实现,但如果有比较复杂的触发条件就是用到opensynphony的开源定时服务包quartz。spring为quartz提供了良好的支持。spring中相关的定时服务的包在org.springframework.scheduling.quartz.*中。 

      在quartz中有两种方式来实现定时服务,一种方法是实现QuartzJobBean,另一种方法是写一个服务类,用spring提供的类型进行包装成quartzjobbean(貌似adapter).

     先用第一种方法来写一个示

package quartz1;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class LogJob extends QuartzJobBean {
    
private int timeout;

    
public int getTimeout() {
        
return timeout;
    }


    
public void setTimeout(int timeout) {
        
this.timeout = timeout;
    }


    
protected void executeInternal(JobExecutionContext arg0)
            
throws JobExecutionException {
        System.out.println(
"quartz do......");

    }


}

这个服务类写好后,再配置一个触发器,就能运行了。

spring中的配置如下:

 

<bean id="logJob1"
        class
="org.springframework.scheduling.quartz.JobDetailBean">
        
<property name="jobClass">
            
<value>quartz1.LogJob</value>
        
</property>
        
<property name="jobDataAsMap">
            
<map>
                
<entry key="timeout">
                    
<value>10</value>
                
</entry>
            
</map>
        
</property>
    
</bean>
    
<bean id="trigger1"
        class
="org.springframework.scheduling.quartz.SimpleTriggerBean">
        
<property name="jobDetail">
            
<ref bean="logJob1"></ref>
        
</property>

        
<property name="startDelay">
            
<value>5000</value>
        
</property>
        
<property name="repeatInterval">
            
<value>2000</value>
        
</property>
        
<property name="repeatCount">
            
<value>0</value>
        
</property>
    
</bean>

    
<bean id="sfb"
        class
="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        
<property name="triggers">
            
<list>
                
<ref local="trigger1" />
            
</list>
        
</property>
    
</bean>

定时服务如何启动呢,有人看过SchedulerFactoryBean可能会注意到一个start()方法,错误的利用此方法来启动定时服务。其实定时服务是不需要启动的,在spring配置文件装载时定时服务会自动启动。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值