Quartz与Spring结合时如何动态更新Job的启动时间

动态更新的Java类如下:

import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class QuartzTest {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "/applicationContext.xml");
    private static String INSTANCE_NAME = "DEFAULT";

    public void test() throws Exception {
        Scheduler sch = (Scheduler) context.getBean("BatchJobStarting");
        JobDetail myJob = sch.getJobDetail("CleanLogJob", INSTANCE_NAME);
        CronTrigger newTrigger = new CronTrigger("trig_batch", INSTANCE_NAME,
                "0/3 * * * * ?");
        JobDetail newJob = (JobDetail) myJob.clone();
        sch.deleteJob("CleanLogJob", INSTANCE_NAME);
        sch.scheduleJob(newJob, newTrigger);
    }

    public static void main(String[] args) {
        QuartzTest qt = new QuartzTest();
        try {
            qt.test();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

 代码写得比较简陋,主要是test()方法,大家可以根据自己的实际情况再发挥,例如,如果你是用Web方式改的话,context的获取可以直接从WebApplicationContext中获取。

applicationContext.xml的配置如下:

<bean id="CleanLogJob"
        class="org.springframework.scheduling.quartz.JobDetailBean">
        <property name="jobClass">
            <value>com.***.***.biz.log.CleanLogJob</value>
        </property>
        <property name="jobDataAsMap">
            <map>
                <entry key="logService">
                    <ref bean="LogService" />
                </entry>
            </map>
        </property>
    </bean>
    <bean id="CleanLogJobTrigger"
        class="org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail">
            <ref bean="CleanLogJob" />
        </property>
        <property name="cronExpression">
            <value>0 0 0 * * ?</value>
        </property>
    </bean>
    <bean id="BatchJobStarting"
        class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="CleanLogJobTrigger" />
            </list>
        </property>
    </bean>

 

你可能感兴趣的:(spring,bean,xml,quartz,qt)