Spring4.0.6 +Quartz 2.2.1动态添加、修改、删除、关闭定时任务

说在前面:

Spring Quartz动态添加、修改、删除、关闭定时任务, 无非就是将
《Spring task quartz 示例 一文中的Spring quartz示例 和 《Quartz 2.2 动态添加、修改和删除定时任务》QuartzManager.java进行整合。
相对Spring Task的动态添加、修改、删除、关闭定时任务简单了许多。

下面我们进入正题。

需要引入 spring-context-support-4.0.6.RELEASE.jar

**注意版本兼容问题:
Spring+Quartz的版本兼容问题**

代码示例

MyJob.java

import java.util.Date;

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

public class MyJob implements Job{

    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println(new Date() + ": job 1 doing something...");
    }
}

MyJob2.java

import java.util.Date;

public class MyJob{

    public void doSomething(){
        System.out.println(new Date() + ": job 2 doing something...");
    }
}

spring-mvc.xml

  
<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-3.0.xsd"  
    default-lazy-init="true">  

      
    <bean id="myJob2" class="quartz.MyJob2">bean>  

      
      
    <bean id="jobtask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">  
          
        <property name="targetObject" ref="myJob2" />  
          
        <property name="targetMethod" value="doSomething" />  
          
        <property name ="concurrent" value ="false"  />          
    bean>  

      
    <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean ">  
        <property name="jobDetail" ref="jobtask" />  
          
        <property name="cronExpression" value="0/1 * * * * ?" />  
    bean>  

      
    <bean id="startQuertz" lazy-init="true" autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
        <property name="triggers">  
            <list>  
                <ref bean="cronTrigger" />  
            list>  
        property>  
    bean>  

         
    <bean id="quartzManager" class="quartz.QuartzManager" lazy-init="false" init-method="startJobs" >  
          
        <property name="scheduler" ref="startQuertz" />  
    bean>   

beans>  

QuartzManager.java

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;

public class QuartzManager {

    private Scheduler scheduler;  

    /** 
     * @Description: 添加一个定时任务 
     *  
     * @param jobName 任务名 
     * @param jobGroupName  任务组名 
     * @param triggerName 触发器名 
     * @param triggerGroupName 触发器组名 
     * @param jobClass  任务 
     * @param cron   时间设置,参考quartz说明文档  
     */  
    @SuppressWarnings({ "unchecked", "rawtypes" })  
    public void addJob(String jobName, String jobGroupName, 
            String triggerName, String triggerGroupName, Class jobClass, String cron) {  
        try {  
            // 任务名,任务组,任务执行类
            JobDetail jobDetail= JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName).build();

            // 触发器  
            TriggerBuilder triggerBuilder = TriggerBuilder.newTrigger();
            // 触发器名,触发器组  
            triggerBuilder.withIdentity(triggerName, triggerGroupName);
            triggerBuilder.startNow();
            // 触发器时间设定  
            triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
            // 创建Trigger对象
            CronTrigger trigger = (CronTrigger) triggerBuilder.build();

            // 调度容器设置JobDetail和Trigger
            scheduler.scheduleJob(jobDetail, trigger);  

            // 启动  
            if (!scheduler.isShutdown()) {  
                scheduler.start();  
            }  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  

    /** 
     * @Description: 修改一个任务的触发时间
     *  
     * @param jobName 
     * @param jobGroupName
     * @param triggerName 触发器名
     * @param triggerGroupName 触发器组名 
     * @param cron   时间设置,参考quartz说明文档   
     */  
    public void modifyJobTime(String jobName, 
            String jobGroupName, String triggerName, String triggerGroupName, String cron) {  
        try {  
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);  
            if (trigger == null) {  
                return;  
            }  

            String oldTime = trigger.getCronExpression();  
            if (!oldTime.equalsIgnoreCase(cron)) { 
                /** 方式一 :调用 rescheduleJob 开始 */
                // 触发器  
                TriggerBuilder triggerBuilder = TriggerBuilder.newTrigger();
                // 触发器名,触发器组  
                triggerBuilder.withIdentity(triggerName, triggerGroupName);
                triggerBuilder.startNow();
                // 触发器时间设定  
                triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
                // 创建Trigger对象
                trigger = (CronTrigger) triggerBuilder.build();
                // 方式一 :修改一个任务的触发时间
                scheduler.rescheduleJob(triggerKey, trigger);
                /** 方式一 :调用 rescheduleJob 结束 */

                /** 方式二:先删除,然后在创建一个新的Job  */
                //JobDetail jobDetail = scheduler.getJobDetail(JobKey.jobKey(jobName, jobGroupName));  
                //Class jobClass = jobDetail.getJobClass();  
                //removeJob(jobName, jobGroupName, triggerName, triggerGroupName);  
                //addJob(jobName, jobGroupName, triggerName, triggerGroupName, jobClass, cron); 
                /** 方式二 :先删除,然后在创建一个新的Job */
            }  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  

    /** 
     * @Description: 移除一个任务 
     *  
     * @param jobName 
     * @param jobGroupName 
     * @param triggerName 
     * @param triggerGroupName 
     */  
    public void removeJob(String jobName, String jobGroupName,  
            String triggerName, String triggerGroupName) {  
        try {  
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);

            scheduler.pauseTrigger(triggerKey);// 停止触发器  
            scheduler.unscheduleJob(triggerKey);// 移除触发器  
            scheduler.deleteJob(JobKey.jobKey(jobName, jobGroupName));// 删除任务  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  

    /** 
     * @Description:启动所有定时任务 
     */  
    public void startJobs() {  
        try {  
            scheduler.start();  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  

    /** 
     * @Description:关闭所有定时任务 
     */  
    public void shutdownJobs() {  
        try {  
            if (!scheduler.isShutdown()) {  
                scheduler.shutdown();  
            }  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }

    public Scheduler getScheduler() {
        return scheduler;
    }

    public void setScheduler(Scheduler scheduler) {
        this.scheduler = scheduler;
    }  

}

测试类1:Test.java

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test{

    public static void main(String[] args) throws BeansException {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-mvc.xml");  
        QuartzManager quartzManager = (QuartzManager) ctx.getBean("quartzManager");
        try {  
            System.out.println("【系统启动】开始(每1秒输出一次)...");        
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }
}

执行结果:
Spring4.0.6 +Quartz 2.2.1动态添加、修改、删除、关闭定时任务_第1张图片

测试类2:Test.java

public static void main(String[] args) throws BeansException {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-mvc.xml");  
        QuartzManager quartzManager = (QuartzManager) ctx.getBean("quartzManager");
        try {  
            System.out.println("【系统启动】开始(每1秒输出一次 job2)...");    

            Thread.sleep(5000); 
            System.out.println("【增加job1启动】开始(每1秒输出一次)...");  
            quartzManager.addJob("test", "test", "test", "test", MyJob.class, "0/1 * * * * ?");    

            Thread.sleep(5000);    
            System.out.println("【修改job1时间】开始(每2秒输出一次)...");    
            quartzManager.modifyJobTime("test", "test", "test", "test", "0/2 * * * * ?");    

            Thread.sleep(10000);    
            System.out.println("【移除job1定时】开始...");    
            quartzManager.removeJob("test", "test", "test", "test");    

            // 关掉任务调度容器
            // quartzManager.shutdownJobs();
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }

执行结果:
Spring4.0.6 +Quartz 2.2.1动态添加、修改、删除、关闭定时任务_第2张图片

因此我们只要在测试的方法中, 将cron的表达式改成从数据库中查出来,然后设置进去,然后接着再封装一个action, 改变数据库的cron值,调用action请求就可以实现 Spring Quartz动态添加、修改、删除、关闭定时任务。

你可能感兴趣的:(Java)