Quartz總結(二):定時任務中使用業務類(XXService)


零、引言

上一篇文章:講到了Spring集成Quartz的幾種基本方法。

在實際使用的時候,往往會在定時任務中調用某個業務類中的方法,此時使用QuartzJobBean和MethodInvokeJobDetailFactoryBean的區別就出來了。

一、QuartzJobBean

在繼承QuartzJobBean的Job類中,使用XXService的時候,會報 空指針異常,原因是因為使用此方法的時候Job對象的創建時Quartz創建的,而XXXService是通過Spring創建的,兩者不是同一個系統的,所以在Job類中使用由Spring管理的對象就會報空指針異常。

其具體使用場景如下:

public class TestJob extends QuartzJobBean {

    @Autowired
    private TestService testSevice;
    
    @Override
    protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
        testSevice.sayHi();
        System.out.println(TimeUtils.getCurrentTime());
    }
}

解決方式就是替換系統默認的SchedulerFactory

public class BsQuartzJobFactory extends AdaptableJobFactory {

    @Autowired
    private AutowireCapableBeanFactory capableBeanFactory;
    
    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        
        Object jobInstance=super.createJobInstance(bundle);
        capableBeanFactory.autowireBean(jobInstance);
        return super.createJobInstance(bundle);
    }
}

然后在XML中配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <bean id="quartzFactory" class="com.mc.bsframe.job.BsQuartzJobFactory"></bean>

    <bean id="jobDetail" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
        <property name="jobClass" value="com.mc.bsframe.job.TestJob"></property>
        <property name="durability" value="true"></property>
    </bean>

    <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
        <property name="jobDetail" ref="jobDetail" />
        <property name="startDelay" value="3000" />
        <property name="repeatInterval" value="2000" />
    </bean>

    <!-- 總管理類 如果將lazy-init='false'那么容器啟動就會執行調度程序 -->
    <bean id="startQuertz" lazy-init="false" autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="jobFactory" ref="quartzFactory"></property>
        <!-- 管理trigger -->
        <property name="triggers">
            <list>
                <ref bean="simpleTrigger" />
            </list>
        </property>
    </bean>
</beans>

二、使用MethodInvokeJobDetailFactoryBean

因為對象的創建時Spring進行創建的,所以可以直接使用。基於此,推薦大家使用此種方式進行集成,方便,簡單。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM