一个Main测试的Spring+Quartz配置动态定时任务的方法

首先参考文章

http://sulaohuai.blog.51cto.com/10674946/1702625

里面的示例写的不是太全,自己揣测大致补全了代码,亲测可用。

1、Main方法的测试类

package com.ims.scheduler;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class Main {

    public static void main(String[] args) throws SchedulerException, InterruptedException {
        // Job的配置信息,可以从数据库或配置文件中获取
        List<JobParameter> list = new ArrayList<JobParameter>();
        String jobGroup = "JobGroup1";
        for (int i = 1; i < 4; i++) {
            JobParameter param = new JobParameter();
            param.setJobName("Job" + i);
            param.setJobGroup(jobGroup);
            param.setCronExpression("0/5 * * * * ?");
            param.setDescription("Execute job " + i + " every 5 seconds ...");
            list.add(param);
        }
        AbstractApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        try {
            Scheduler scheduler = (Scheduler) context.getBean("schedulerFactoryBean");
            // ### 创建并启动job ###
            for (JobParameter param : list) {
                // 构建job信息
                JobDetail jobDetail = JobBuilder.newJob(MyJob.class).withIdentity(param.getJobName(), param.getJobGroup()).build();

                // 表达式调度构建器
                CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(param.getCronExpression());

                // 按cronExpression表达式构建trigger
                CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(param.getJobName(), param.getJobGroup()).withSchedule(scheduleBuilder).build();

                // 放入参数,运行时的方法可以获取
                jobDetail.getJobDataMap().put("jobParam", param);
                scheduler.scheduleJob(jobDetail, trigger);
            }

            Thread.sleep(50000);

            // ### 移除job3 ###
            Thread.sleep(5000);
            System.out.println("### 移除job3 ###");
            scheduler.deleteJob(JobKey.jobKey("Job3", jobGroup));

            // ### 暂停job1和job2 ###
            Thread.sleep(5000);
            System.out.println("### 暂停job1和job2 ###");
            scheduler.pauseJob(JobKey.jobKey("Job1", jobGroup));
            scheduler.pauseJob(JobKey.jobKey("Job2", jobGroup));

            // ### 再次启动job1 ###
            Thread.sleep(5000);
            System.out.println("### 再次启动job1 ###");
            scheduler.resumeJob(JobKey.jobKey("Job1", jobGroup));

            // ### 修改job1的cron ###
            Thread.sleep(5000);
            System.out.println("### 修改job1的cron为每3秒执行一次 ###");
            TriggerKey triggerKey = TriggerKey.triggerKey("Job1", jobGroup);
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/3 * * * * ?");
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();

            // 获取job参数并修改描述
            JobParameter jobParam = (JobParameter) scheduler.getJobDetail(JobKey.jobKey("Job1", jobGroup))
                                                                  .getJobDataMap().get(JobParameter.JOB_PARAM);
            jobParam.setCronExpression("0/3 * * * * ?");
            jobParam.setDescription("Execute job 1 every 3 seconds ...");
            scheduler.rescheduleJob(triggerKey, trigger);

            // 打印内存中的所有 Job
            Thread.sleep(5000);
            System.out.println("### 打印内存中的所有 Job的状态 ###");
            Set<TriggerKey> triggerKeys = scheduler.getTriggerKeys(GroupMatcher.anyTriggerGroup());
            for (TriggerKey tKey : triggerKeys) {
                CronTrigger t = (CronTrigger) scheduler.getTrigger(tKey);
                System.out.println("Trigger details: " + t.getJobKey().getName() + ", " + t.getJobKey().getGroup()
                        + ", " + scheduler.getTriggerState(tKey) + ", " + t.getFinalFireTime() + ", "
                        + t.getCronExpression());
            }

        } finally {
            if (context != null) {
                context.close();
            }
            System.out.println("Spring context is closed.");
        }
    }

}

2、引用了几个类
JobParameter

package com.ims.scheduler;

import java.util.Date;

public class JobParameter {
    public static final String JOB_PARAM = "jobParam";
    private String jobName;
    private String jobGroup;
    private String jobTrigger;
    private String status;
    private String cronExpression;
    private Boolean isSync = false;
    private String description;
    private Date updatedTime = new Date();
    public String getJobName() {
        return jobName;
    }
    public void setJobName(String jobName) {
        this.jobName = jobName;
    }
    public String getJobGroup() {
        return jobGroup;
    }
    public void setJobGroup(String jobGroup) {
        this.jobGroup = jobGroup;
    }
    public String getJobTrigger() {
        return jobTrigger;
    }
    public void setJobTrigger(String jobTrigger) {
        this.jobTrigger = jobTrigger;
    }
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    public String getCronExpression() {
        return cronExpression;
    }
    public void setCronExpression(String cronExpression) {
        this.cronExpression = cronExpression;
    }
    public Boolean getIsSync() {
        return isSync;
    }
    public void setIsSync(Boolean isSync) {
        this.isSync = isSync;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public Date getUpdatedTime() {
        return updatedTime;
    }
    public void setUpdatedTime(Date updatedTime) {
        this.updatedTime = updatedTime;
    }
    public static String getJobParam() {
        return JOB_PARAM;
    }


}

MyJob类

package com.ims.scheduler;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class MyJob implements Job{
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobParameter jobParam = (JobParameter) jobExecutionContext.getJobDetail().getJobDataMap()
                .get(JobParameter.JOB_PARAM);
        if (jobParam != null) {
            System.out.println(jobParam.getDescription());
        } else {
            System.out.println("Hey, can't find job parameter ...:)");
        }
    }

}

3、SpringXML文件
只需要定义一个bean

<bean id="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    </bean>

你可能感兴趣的:(spring)