quartz+Spring实现动态配置定时任务

1. 引入jar包:quartz-jobs-2.2.3.jar,quartz-2.2.3.jar

2. 添加配置文件quartz.xml

3. 创建QuartzManager定时任务管理工具类

4. 创建定时任务实现类,将业务写在execute( )方法中

5. 根据业务需求管理定时任务

quartz.xml



    
    
    
    

    
    
    
        
        
        
        
        
        
    

    
    
        
        
        
    

    
    
        
            
                
                
            
        
    

    
    
        
        
    

QuartzManager.java

import java.util.List;

import javax.annotation.Resource;

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 {
    @Resource
    private ScenarioMapper scenarioMapper;
    
    private Scheduler scheduler;

    public Scheduler getScheduler() {
        return scheduler;
    }

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

    /**
     * 功能: 添加一个定时任务
     * @param jobName 任务名
     * @param jobGroupName  任务组名
     * @param triggerName 触发器名
     * @param triggerGroupName 触发器组名
     * @param jobClass  任务的类类型  eg:TimedMassJob.class
     * @param cron   时间设置 表达式,参考quartz说明文档
     */
    public void addJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName, Class jobClass, String cron,Object...objects) {
        try {
            // 任务名,任务组,任务执行类
            JobDetail jobDetail= JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName).build();
            // 触发器
            if(objects!=null){
                for (int i = 0; i < objects.length; i++) {
                    //该数据可以通过Job中的JobDataMap dataMap = context.getJobDetail().getJobDataMap();来进行参数传递值
                    jobDetail.getJobDataMap().put("data"+(i+1), objects[i]);
                }
            }
            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);
        }
    }

    /**
     * 功能:修改一个任务的触发时间
     * @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)) {
                // 触发器
                TriggerBuilder triggerBuilder = TriggerBuilder.newTrigger();
                // 触发器名,触发器组
                triggerBuilder.withIdentity(triggerName, triggerGroupName);
                triggerBuilder.startNow();
                // 触发器时间设定
                triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
                // 创建Trigger对象
                trigger = (CronTrigger) triggerBuilder.build();
                // 方式一 :修改一个任务的触发时间
                scheduler.rescheduleJob(triggerKey, trigger);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 功能: 移除一个任务
     * @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);
        }
    }

    /**
     *
     * 功能:启动所有定时任务,可以在这里初始化数据库中的定时任务
     */
    public void startJobs() {
        try {
            scheduler.start();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 功能:关闭所有定时任务
     */
    public void shutdownJobs() {
        try {
            if (!scheduler.isShutdown()) {
                scheduler.shutdown();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

cron格式转化工具类

import java.text.DecimalFormat;
public class QuartzCronDateUtils {
    /***
     *根据自己的需要编写转化方法即可  * * * * * ?:秒 分 时 日 月 星期(日和星期冲突,需把一个设为?)
     * @param  time  HH:mm:ss
     * @param  weekdays 星期(bit0:周日;bit1:周一;...;bit6:周六)
     * @return
     */
    public static String getCron(String time,int weekdays){
        String[] str = time.split(":");
        String second = str[2];
        String minute = str[1];
        String hour = str[0];
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(second).append(" ").append(minute).append(" ").append(hour).append(" ? * ");
        String week = Integer.toBinaryString(weekdays);
        DecimalFormat df = new DecimalFormat("0000000");
        week = df.format(Integer.parseInt(week));
        for (int i = 6; i >= 0; i--) {
            if (Integer.valueOf(week.substring(i, i+1)) == 1) {
                stringBuffer.append((7-i) + ",");
            }
        }
        String cron = stringBuffer.toString();
        return cron.substring(0, cron.length()-1);
    }
}

定时任务实现类TaskJob.java

import java.util.List;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.springframework.context.ApplicationContext;
//实现Job接口的execute方法
public class TaskJob implements Job {
    
    private int taskId;
    
    public TaskJob(int taskId) {
        this.taskId = taskId;
    }
    
    public TaskJob() {
    }
    
    public int getTaskId() {
        return taskId;
    }
    
    @Override
    public void execute(JobExecutionContext arg0) {
      //可根据argo参数,获取定时任务的相关属性
          JobDataMap jobDataMap = arg0.getMergedJobDataMap();
          TaskJob jobDemo = (TaskJob)jobDataMap.get("data1");
          System.out.println(jobDemo.taskId);
    }   
}

你可能感兴趣的:(quartz+Spring实现动态配置定时任务)