springboot Quartz 定時任務工具類

FH-Admin發表於2021-07-02
package org.fh.util;

import java.util.Map;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;  
import org.quartz.SchedulerFactory;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;  

/**
 * 說明:定時任務管理類 
 * 作者:FH Admin
 * from:www.fhadmin.cn
 */
public class QuartzManager {  
    private static SchedulerFactory gSchedulerFactory = new StdSchedulerFactory();  //建立一個SchedulerFactory工廠例項
    private static String JOB_GROUP_NAME = "FH_JOBGROUP_NAME";                      //任務組
    private static String TRIGGER_GROUP_NAME = "FH_TRIGGERGROUP_NAME";              //觸發器組

    /**新增一個定時任務,使用預設的任務組名,觸發器名,觸發器組名  
     * @param jobName 任務名
     * @param cls 任務
     * @param time 時間設定,參考quartz說明文件
     */
    public static void addJob(String jobName, Class<? extends Job> cls, String time) {  
        try {  
            Scheduler sched = gSchedulerFactory.getScheduler();                                          //透過SchedulerFactory構建Scheduler物件
            JobDetail jobDetail= JobBuilder.newJob(cls).withIdentity(jobName,JOB_GROUP_NAME).build();    //用於描敘Job實現類及其他的一些靜態資訊,構建一個作業例項
            CronTrigger trigger = (CronTrigger) TriggerBuilder
                    .newTrigger()                                                                         //建立一個新的TriggerBuilder來規範一個觸發器
                    .withIdentity(jobName, TRIGGER_GROUP_NAME)                                            //給觸發器起一個名字和組名
                    .withSchedule(CronScheduleBuilder.cronSchedule(time))
                    .build();
            sched.scheduleJob(jobDetail, trigger);  
            if (!sched.isShutdown()) {  
                sched.start();        // 啟動  
            }  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  

    /**新增一個定時任務,使用預設的任務組名,觸發器名,觸發器組名  (帶引數)
     * @param jobName 任務名
     * @param cls 任務
     * @param time 時間設定,參考quartz說明文件
     */
    public static void addJob(String jobName, Class<? extends Job> cls, String time, Map<String,Object> parameter) {  
        try {  
            Scheduler sched = gSchedulerFactory.getScheduler();                                          //透過SchedulerFactory構建Scheduler物件
            JobDetail jobDetail= JobBuilder.newJob(cls).withIdentity(jobName,JOB_GROUP_NAME).build();    //用於描敘Job實現類及其他的一些靜態資訊,構建一個作業例項
            jobDetail.getJobDataMap().put("parameterList", parameter);                                    //傳引數
            CronTrigger trigger = (CronTrigger) TriggerBuilder
                    .newTrigger()                                                                         //建立一個新的TriggerBuilder來規範一個觸發器
                    .withIdentity(jobName, TRIGGER_GROUP_NAME)                                            //給觸發器起一個名字和組名
                    .withSchedule(CronScheduleBuilder.cronSchedule(time))
                    .build();
            sched.scheduleJob(jobDetail, trigger);  
            if (!sched.isShutdown()) {  
                sched.start();        // 啟動  
            }  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  

    /**新增一個定時任務 
     * @param jobName    任務名 
     * @param jobGroupName    任務組名 
     * @param triggerName    觸發器名 
     * @param triggerGroupName    觸發器組名 
     * @param jobClass    任務 
     * @param time    時間設定,參考quartz說明文件 
     */
    public static void addJob(String jobName, String jobGroupName,  
            String triggerName, String triggerGroupName, Class<? extends Job> jobClass,  
            String time) {  
        try {  
            Scheduler sched = gSchedulerFactory.getScheduler();  
            JobDetail jobDetail= JobBuilder.newJob(jobClass).withIdentity(jobName,jobGroupName).build();// 任務名,任務組,任務執行類
            CronTrigger trigger = (CronTrigger) TriggerBuilder     // 觸發器  
                    .newTrigger()
                    .withIdentity(triggerName, triggerGroupName)
                    .withSchedule(CronScheduleBuilder.cronSchedule(time))
                    .build();
            sched.scheduleJob(jobDetail, trigger);
            if (!sched.isShutdown()) {  
                sched.start();        // 啟動  
            } 
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  

    /**新增一個定時任務  (帶引數)
     * @param jobName    任務名 
     * @param jobGroupName    任務組名 
     * @param triggerName    觸發器名 
     * @param triggerGroupName    觸發器組名 
     * @param jobClass    任務 
     * @param time    時間設定,參考quartz說明文件 
     */
    public static void addJob(String jobName, String jobGroupName,  
            String triggerName, String triggerGroupName, Class<? extends Job> jobClass,  
            String time, Map<String,Object> parameter) {  
        try {  
            Scheduler sched = gSchedulerFactory.getScheduler();  
            JobDetail jobDetail= JobBuilder.newJob(jobClass).withIdentity(jobName,jobGroupName).build();// 任務名,任務組,任務執行類
            jobDetail.getJobDataMap().put("parameterList", parameter);                                //傳引數
            CronTrigger trigger = (CronTrigger) TriggerBuilder     // 觸發器  
                    .newTrigger()
                    .withIdentity(triggerName, triggerGroupName)
                    .withSchedule(CronScheduleBuilder.cronSchedule(time))
                    .build();
            sched.scheduleJob(jobDetail, trigger);
            if (!sched.isShutdown()) {  
                sched.start();        // 啟動  
            } 
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    } 

    /** 修改一個任務的觸發時間(使用預設的任務組名,觸發器名,觸發器組名) 
     * @param jobName    任務名 
     * @param time    新的時間設定
     */
    public static void modifyJobTime(String jobName, String time) {  
        try {  
            Scheduler sched = gSchedulerFactory.getScheduler();                              //透過SchedulerFactory構建Scheduler物件
            TriggerKey triggerKey = TriggerKey.triggerKey(jobName,TRIGGER_GROUP_NAME);         //透過觸發器名和組名獲取TriggerKey
            CronTrigger trigger = (CronTrigger)sched.getTrigger(triggerKey);                //透過TriggerKey獲取CronTrigger
            if (trigger == null) {  
                return;  
            }  
            String oldTime = trigger.getCronExpression();  
            if (!oldTime.equalsIgnoreCase(time)) {  
                JobKey jobKey = JobKey.jobKey(jobName, JOB_GROUP_NAME);                        //透過任務名和組名獲取JobKey
                JobDetail jobDetail = sched.getJobDetail(jobKey); 
                Class<? extends Job> objJobClass = jobDetail.getJobClass();  
                removeJob(jobName);  
                addJob(jobName, objJobClass, time);  
            }  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  

    /**修改一個任務的觸發時間 
     * @param triggerName    任務名稱
     * @param triggerGroupName    傳過來的任務名稱
     * @param time    更新後的時間規則
     */
    public static void modifyJobTime(String triggerName, String triggerGroupName, String time) {  
        try {  
            Scheduler sched = gSchedulerFactory.getScheduler();                              //透過SchedulerFactory構建Scheduler物件
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName,triggerGroupName);     //透過觸發器名和組名獲取TriggerKey
            CronTrigger trigger = (CronTrigger)sched.getTrigger(triggerKey);                //透過TriggerKey獲取CronTrigger
            if (trigger == null)  return;  
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(trigger.getCronExpression());
            String oldTime = trigger.getCronExpression();  
            if (!oldTime.equalsIgnoreCase(time)) {  
                trigger = (CronTrigger)trigger.getTriggerBuilder()        //重新構建trigger
                        .withIdentity(triggerKey)
                        .withSchedule(scheduleBuilder)
                        .withSchedule(CronScheduleBuilder.cronSchedule(time))
                        .build();
                sched.rescheduleJob(triggerKey, trigger);                //按新的trigger重新設定job執行
            }
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  

    /**移除一個任務(使用預設的任務組名,觸發器名,觸發器組名) 
     * @param jobName    任務名稱
     */
    public static void removeJob(String jobName) {  
        try {  
            Scheduler sched = gSchedulerFactory.getScheduler();  
            TriggerKey triggerKey = TriggerKey.triggerKey(jobName,TRIGGER_GROUP_NAME);     //透過觸發器名和組名獲取TriggerKey
            JobKey jobKey = JobKey.jobKey(jobName, JOB_GROUP_NAME);                        //透過任務名和組名獲取JobKey
            sched.pauseTrigger(triggerKey);    // 停止觸發器  
            sched.unscheduleJob(triggerKey);// 移除觸發器  
            sched.deleteJob(jobKey);        // 刪除任務  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  

    /**移除一個任務
     * @param jobName    任務名
     * @param jobGroupName    任務組名
     * @param triggerName    觸發器名
     * @param triggerGroupName    觸發器組名
     */
    public static void removeJob(String jobName, String jobGroupName,String triggerName, String triggerGroupName) {  
        try {  
            Scheduler sched = gSchedulerFactory.getScheduler();  
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName,triggerGroupName);     //透過觸發器名和組名獲取TriggerKey
            JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);                            //透過任務名和組名獲取JobKey
            sched.pauseTrigger(triggerKey);    // 停止觸發器  
            sched.unscheduleJob(triggerKey);// 移除觸發器  
            sched.deleteJob(jobKey);        // 刪除任務  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    } 

    /**
     * 啟動所有定時任務 
     */
    public static void startJobs() {  
        try {  
            Scheduler sched = gSchedulerFactory.getScheduler();  
            sched.start();  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  

    /**
     * 關閉所有定時任務 
     */
    public static void shutdownJobs() {  
        try {  
            Scheduler sched = gSchedulerFactory.getScheduler();  
            if (!sched.isShutdown()) {  
                sched.shutdown();  
            }  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  
}  
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章