spring quartz动态实现对任务的增删改查(可传参数)

        上一篇文章写到了关于定时任务的动态实现,在一些情况下,我们可能需要传参数来实现定时任务,直接贴代码了

QuartzParamUtils,核心类

package com.thinkgem.jeesite.modules.task.quartz.param;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;

import com.thinkgem.jeesite.common.utils.SpringContextHolder;
import com.thinkgem.jeesite.modules.img.dao.GrabPictureDao;
import com.thinkgem.jeesite.modules.img.entity.GrabPicture;
import com.thinkgem.jeesite.modules.task.quartz.QuartzJobFactory;
import com.thinkgem.jeesite.modules.task.quartz.uils.QuartzUtils;

public class QuartzParamUtils {
	private static Logger logger = Logger.getLogger(QuartzJobFactory.class);
    
    private static GrabPictureDao grabPictureDao = SpringContextHolder.getBean(GrabPictureDao.class);
 
    /**
     * @Note : 扫面数据库,查看是否有计划任务的变动
     */
    public static void arrageScheduleJob() {
        try {
 
            List jobList = grabPictureDao.findList(new GrabPicture());
            if (jobList.size() != 0) {
                for (GrabPicture job : jobList) {
                    // Keys are composed of both a name and group, and the name  must be unique within the group
                    TriggerKey triggerKey = TriggerKey.triggerKey(job.getName(), job.getJobGroup());
                    // 获取trigger
                    CronTrigger trigger = (CronTrigger) QuartzUtils.scheduler.getTrigger(triggerKey);
                    // 不存在,创建一个
                    if (null == trigger) {
                        createSheduler(QuartzUtils.scheduler, job);
                    } else {// Trigger已存在,那么更新相应的定时设置
                        updateScheduler(QuartzUtils.scheduler, job, triggerKey, trigger);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 更新相应的定时设置 根据job_status做相应的处理
     * 
     * @param scheduler
     * @param job
     * @param triggerKey
     * @param trigger
     * @throws SchedulerException
     */
    private static void updateScheduler(Scheduler scheduler, GrabPicture job, TriggerKey triggerKey, CronTrigger trigger)
            throws SchedulerException {
        if (job.getStatus().equals("1")) {// 0禁用 1启用
            if (!trigger.getCronExpression().equalsIgnoreCase(job.getCron())) {
                // 表达式调度构建器
                CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCron());
                // 按新的cronExpression表达式重新构建trigger
                trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
                // 按新的trigger重新设置job执行
                scheduler.rescheduleJob(triggerKey, trigger);
                logger.info(job.getJobGroup() + "." + job.getName() + " 更新完毕,目前cron表达式为:" + job.getCron());
            }
        } else if (job.getStatus().equals("0")) {
            scheduler.pauseTrigger(triggerKey);// 停止触发器
            scheduler.unscheduleJob(triggerKey);// 移除触发器
            scheduler.deleteJob(trigger.getJobKey());// 删除任务
            logger.info(job.getJobGroup() + "." + job.getName() + "删除完毕");
        }
 
    }
 
    /**
     * 创建一个定时任务,并做安排
     * 
     * @param scheduler
     * @param job
     * @throws SchedulerException
     * @throws Exception
     */
    public static void createSheduler(Scheduler scheduler, GrabPicture job) throws Exception {
        // 在工作状态可用时,即job_status = 1 ,开始创建
        if (job.getStatus().equals("1")) {
            // 新建一个基于Spring的管理Job类
        	JobDetailFactoryBean jobDetailFactoryBean = new JobDetailFactoryBean();
        	jobDetailFactoryBean.setName(job.getName());
        	//jobDetailFactoryBean.setJobClass(job.getClazz().getClass());
        	jobDetailFactoryBean.setJobClass(MyJobClass.class);
        	JobDataMap jobDataMap = new JobDataMap();
        	jobDataMap.put("scheduleJob", job);
        	jobDetailFactoryBean.setJobDataMap(jobDataMap);
        	
        	Map jobDataAsMap = new HashMap<>();
            jobDataAsMap.put("targetObject","test");             //作业对象
            jobDataAsMap.put("targetMethod","method");                 //作业方法
            jobDataAsMap.put("arguments","args");                 //作业方法的参数
            jobDetailFactoryBean.setJobDataAsMap(jobDataAsMap); 
        	
        	
        	jobDetailFactoryBean.afterPropertiesSet();

            JobDetail jobDetail = jobDetailFactoryBean.getObject();  //获取JobDetail对象
            //String cronExpression = createCronExpression(targetTime);//创建cron表达式
            // 表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCron());
            // 根据cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(job.getName(),job.getJobGroup())
                    .withSchedule(scheduleBuilder).build();
            // 注入到管理类
            scheduler.scheduleJob(jobDetail, trigger);
        	
        	
        	
          
        }
    }
    
    
    /**
     * 更新相应的定时设置 根据job_status做相应的处理
     * 
     * @param scheduler
     * @param job
     * @param triggerKey
     * @param trigger
     * @throws SchedulerException
     */
    public static void updateScheduler(GrabPicture job)
            throws Exception {
    	Scheduler scheduler = QuartzUtils.scheduler;
    	TriggerKey triggerKey = TriggerKey.triggerKey(job.getName(), job.getJobGroup());
        // 获取trigger
        CronTrigger trigger = (CronTrigger) QuartzUtils.scheduler.getTrigger(triggerKey);
        // 不存在,创建一个
        if (null == trigger) {
        	createSheduler(scheduler, job);
        	return;
        }
        if (job.getStatus().equals("1")) {// 0禁用 1启用
            if (!trigger.getCronExpression().equalsIgnoreCase(job.getCron())) {
                // 表达式调度构建器
                CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCron());
                // 按新的cronExpression表达式重新构建trigger
                trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
                // 按新的trigger重新设置job执行
                scheduler.rescheduleJob(triggerKey, trigger);
                logger.info(job.getJobGroup() + "." + job.getName() + " 更新完毕,目前cron表达式为:" + job.getCron());
            }
        } else if (job.getStatus().equals("0")) {
            scheduler.pauseTrigger(triggerKey);// 停止触发器
            scheduler.unscheduleJob(triggerKey);// 移除触发器
            scheduler.deleteJob(trigger.getJobKey());// 删除任务
            logger.info(job.getJobGroup() + "." + job.getName() + "删除完毕");
        }
 
    }
    
    
    /**
     * 更新相应的定时设置 根据job_status做相应的处理
     * 
     * @param scheduler
     * @param job
     * @param triggerKey
     * @param trigger
     * @throws SchedulerException
     */
    public static void deleteScheduler(GrabPicture job)
            throws Exception {
    	Scheduler scheduler = QuartzUtils.scheduler;
    	TriggerKey triggerKey = TriggerKey.triggerKey(job.getName(), job.getJobGroup());
        // 获取trigger
        CronTrigger trigger = (CronTrigger) QuartzUtils.scheduler.getTrigger(triggerKey);
        // 不存在,创建一个
        if (null == trigger) {
        	return;
        }
        scheduler.pauseTrigger(triggerKey);// 停止触发器
        scheduler.unscheduleJob(triggerKey);// 移除触发器
        scheduler.deleteJob(trigger.getJobKey());// 删除任务
        logger.info(job.getJobGroup() + "." + job.getName() + "删除完毕");
    }
}

执行定时任务的类MyJobClass

package com.thinkgem.jeesite.modules.task.quartz.param;

import java.lang.reflect.Method;

import org.apache.log4j.Logger;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.thinkgem.jeesite.modules.img.entity.GrabPicture;

/**
 * 带参的JobClass
 * Created by xiaoming on 2017/5/4.
 */
public class MyJobClass extends QuartzJobBean {
	private static Logger logger = Logger.getLogger(MyJobClass.class);
	
    private String targetObject;   //执行job的对象
    private String targetMethod;   //执行job的方法
    private Object arguments;      //执行job的方法参数(如果方法不带参可以删除此参数)
    private ApplicationContext ctx;//ApplicationContext

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {

        try {
        	JobDataMap jobDataMap = context.getMergedJobDataMap();
        	GrabPicture scheduleJob = (GrabPicture)jobDataMap.get("scheduleJob");
        	System.out.println(scheduleJob.getCron());
        	System.out.println(context.getMergedJobDataMap());
        	
        	System.out.println("测试");
        	
        	System.out.println("targetObject:" + targetObject);
        	System.out.println("targetMethod:" + targetMethod);
        	System.out.println("arguments:" + arguments);
        	
        	
        	
           
        } catch (Exception e) {
            logger.error(e);
        }
    }
    //以下是注入方法
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.ctx = applicationContext;
    }

    public void setTargetObject(String targetObject) {
        this.targetObject = targetObject;
    }

    public void setTargetMethod(String targetMethod) {
        this.targetMethod = targetMethod;
    }

    public void setArguments(Object arguments) {
        this.arguments = arguments;
    }
}

你可能感兴趣的:(spring,quartz)