码迷,mamicode.com
首页 > 编程语言 > 详细

一个Spring Scheduler (Quartz) 动态添加,删除,修改任务的例子

时间:2015-10-14 01:49:37      阅读:310      评论:0      收藏:0      [点我收藏+]

标签:schdule quartz 定时任务

要求


根据任务清单执行不定数量,不定频率的定时任务。并且需要动态添加,删除,修改任务。


代码


public class JobExample { 
    public static void main(String[] args) throws Exception {
        // 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("dynamic-jobs.xml");
        try {
            Scheduler scheduler = (Scheduler) context.getBean("scheduler");
            // ### 创建并启动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);
            }
            // ### 移除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.");
        }
    }
}
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();
    getter & setter ...
}
public class MyJob implements Job {
    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 ...:)");
        }
    }
}


dynamic-jobs.xml

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


执行结果


Execute job 1 every 5 seconds ...

Execute job 2 every 5 seconds ...

Execute job 3 every 5 seconds ...

### 移除job3 ###

Execute job 1 every 5 seconds ...

Execute job 2 every 5 seconds ...

### 暂停job1和job2 ###

### 再次启动job1 ###

Execute job 1 every 5 seconds ...

Execute job 1 every 5 seconds ...

### 修改job1的cron为每3秒执行一次 ###

Execute job 1 every 3 seconds ...

Execute job 1 every 3 seconds ...

### 打印内存中的所有 Job的状态 ###

Execute job 1 every 3 seconds ...

Trigger details: Job1, JobGroup1, NORMAL, null, 0/3 * * * * ?

Trigger details: Job2, JobGroup1, PAUSED, null, 0/5 * * * * ?


版本信息


Quartz版本:2.2.1

Spring版本:3.2.13


参考资料


http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html#scheduling-quartz

http://www.meiriyouke.net/?p=82


完整例子代码见附件


一个Spring Scheduler (Quartz) 动态添加,删除,修改任务的例子

标签:schdule quartz 定时任务

原文地址:http://sulaohuai.blog.51cto.com/10674946/1702625

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!