Quartz总结(二):定时任务中使用业务类(XXService)

零、引言spring

上一篇文章:讲到了Spring集成Quartz的几种基本方法。ide

在实际使用的时候,每每会在定时任务中调用某个业务类中的方法,此时使用QuartzJobBean和MethodInvokeJobDetailFactoryBean的区别就出来了。spa

1、QuartzJobBean指针

在继承QuartzJobBean的Job类中,使用XXService的时候,会报 空指针异常,缘由是由于使用此方法的时候Job对象的建立时Quartz建立的,而XXXService是经过Spring建立的,二者不是同一个系统的,因此在Job类中使用由Spring管理的对象就会报空指针异常。code

其具体使用场景以下:xml

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中配置:blog

<?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>

2、使用MethodInvokeJobDetailFactoryBean继承

由于对象的建立时Spring进行建立的,因此能够直接使用。基于此,推荐你们使用此种方式进行集成,方便,简单。get

相关文章
相关标签/搜索