Spring中使用Quartz的兩種方式

做業類是否繼承QuartzJobBean

  • 繼承
  • 不繼承

不繼承QuartzJobBean,聲明JobDetail時,使用MethodInvokingJobDetailFactoryBeanspring

繼承QuartzJobBean,聲明JobDetail時,使用JobDetailFactoryBeanui

任務調度的觸發時機

  • 每隔指定時間觸發一次:觸發器使用SimpleTriggerBean
  • 每到指定時間觸發一次:觸發器使用CronTriggerBean

這兩種觸發方式均可以和兩種做業繼承方式相互組合來使用。

也就是有四種寫法。

舉個例子:

不繼承QuartzJobBean,由SimpleTriggerBean觸發

<bean id="simpleJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject" ref="myBean"/>
        <property name="targetMethod" value="printMessage"/>
    </bean>


<!-- Run the job every 2 seconds with initial delay of 1 second -->
    <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
        <property name="jobDetail" ref="simpleJobDetail"/>
        <property name="startDelay" value="1000"/>
        <property name="repeatInterval" value="2000"/>
    </bean>
public class MyBean {

    public void printMessage(){
        System.out.println("不繼承QuartzJobBean的做業類。called by MethodInvokingJobDetailFactoryBean using SimpleTriggerFactoryBean");
    }
}

不繼承QuartzJobBean,由CronTriggerBean觸發

繼承QuartzJobBean,由SimpleTirggerBean觸發

繼承QuartzJobBean,由CronTriggerBean觸發

public class ScheduledJob extends QuartzJobBean {

    private AnotherBean anotherBean;

    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        anotherBean.printMessage();
    }

    public void setAnotherBean(AnotherBean anotherBean) {
        this.anotherBean = anotherBean;
    }
}
public class AnotherBean {
    public void printMessage(){
        System.out.println("繼承QuartzJobBean的做業類,經過AnotherBean傳遞數據。called by JobDetailFactoryBean using CronTriggerFactoryBean");
    }
}
<!-- For times when you need more complex processing, passing data to the scheduled job -->
    <bean name="complexJobDetail" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
        <property name="jobClass" value="com.penelope.quickstart.jobs.ScheduledJob"/>
        <property name="jobDataAsMap">
            <map>
                <entry key="anotherBean" value-ref="anotherBean"/>
            </map>
        </property>
        <property name="durability" value="true"/>
    </bean>


<!-- Run the job every 5 seconds only on Weekends -->
    <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail" ref="complexJobDetail"/>
        <property name="cronExpression" value="0/5 * * ? * SAT-SUN"/>
    </bean>

第二個例子是複雜的,在任務類中調用另外一個Bean的方法。另外一個Bean就是該做業類的JobData。使用jobDataAsMap屬性,在JobDetail中聲明。this

小菜蟲使用jobDataMap屬性傳遞AnotherBean失敗,緣由不明。。。往後填坑。code

相關文章
相關標籤/搜索