002-使用java类调用quartz

一、工具类

package com.tech.jin.jobScheduler;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

public class JobUtil {
    
    private static Logger logger = Logger.getLogger(JobUtil.class);
    private static StdSchedulerFactory schedulerFactory = null;
    
    private JobUtil(){}
    
    /**
     * 调度器factory
     * @return
     */
    private static synchronized SchedulerFactory getSchedulerFactory(){
        if(schedulerFactory==null){
            
            schedulerFactory = new StdSchedulerFactory();
            
            Properties p = new Properties();
            p.put("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool");
            p.put("org.quartz.threadPool.threadCount", "10");
            
            try {
                schedulerFactory.initialize(p);
            } catch (SchedulerException e) {
                logger.info(e);
            }
        }
        return schedulerFactory;
    }
    
    /**
     * 添加任务
     * @param job 要调用的job类
     * @param jobName job名称
     * @param cronExpression 任务触发时间表达式
     * @param param 需要用到的参数,可在job类中的context获得
     */
    public static void addJob(Job job,String jobName,String cronExpression,Map param){
        Scheduler scheduler = null;
        try {
            
            removeJob(jobName, job.getClass().getCanonicalName()+"Group");//删除原任务
            
            scheduler = getSchedulerFactory().getScheduler();
            
            JobDetail jobDetail = getJobDetail(job, jobName,param);
            String jobGroup = jobDetail.getGroup();
            CronTrigger cronTrigger = getCronTrigger(job, jobName,jobGroup, cronExpression);
            
            scheduler.scheduleJob(jobDetail, cronTrigger);
            
            logger.info("添加任务:"+jobName);

            startScheduler();
            
        } catch (SchedulerException e) {
            logger.error(e);
        }
        
    }
    
    /**
     * 对外停止任务调度器方法
     */
    public static void stopJob(){
        shutdownScheduler();
    }
    
    /**
     * 启动调度器
     */
    protected static void startScheduler(){
        Scheduler scheduler = null;
        try {
            scheduler = getSchedulerFactory().getScheduler();
            //如果调度器未启动,启动调度器
            if(scheduler!=null&&!scheduler.isStarted()){
                scheduler.start();
            }
        } catch (SchedulerException e) {
            logger.error(e);
        }
    }
    
    /**
     * 关闭调度器,关闭后任务也都清除
     */
    protected static void shutdownScheduler(){
        Scheduler scheduler = null;
        try {
            scheduler = getSchedulerFactory().getScheduler();
            //如果调度器未关闭,关闭调度器
            if(scheduler!=null&&!scheduler.isShutdown()){
                scheduler.shutdown();
            }
        } catch (SchedulerException e) {
            logger.error(e);
        }
    }
    
    /**
     * 获取JobDetail
     * @param job
     * @param param
     * @return
     */
    protected static JobDetail getJobDetail(Job job,String jobName,Map param){
        Class jobClazz = job.getClass();
        if(jobName==null||"".equals(jobName)){
            jobName = jobClazz.getCanonicalName();
        }
        String jobGroup = jobClazz.getCanonicalName()+"Group";
        
        JobDetail jobDetail = new JobDetail();
        jobDetail.setDurability(true);
        jobDetail.setRequestsRecovery(true);
        jobDetail.setName(jobName);
        jobDetail.setGroup(jobGroup);
        jobDetail.setJobClass(jobClazz);
        
        if(param!=null&&param.size()>0){
            JobDataMap jobDataMap = new JobDataMap(param);//存放参数
            jobDetail.setJobDataMap(jobDataMap);
            
            logger.info("任务 "+jobName+" jobDetail存放的参数:"+param);
        }
        
        return jobDetail;
    }
    
    /**
     * 获取触发器
     * @param job
     * @param jobName
     * @param cronExpression
     * @return
     */
    protected static CronTrigger getCronTrigger(Job job,String jobName,String jobGroup,String cronExpression){
        Class jobClazz = job.getClass();
        String triggerName = jobClazz.getCanonicalName()+"Trigger";
        String triggerGroup = jobClazz.getCanonicalName()+"TriggerGroup";
        
        CronTrigger cronTrigger = new CronTrigger();
        cronTrigger.setName(triggerName);
        cronTrigger.setGroup(triggerGroup);
        cronTrigger.setJobName(jobName);
        cronTrigger.setJobGroup(jobGroup);
        try {
            cronTrigger.setCronExpression(cronExpression);//触发任务的时间表达式
        } catch (ParseException e) {
            logger.error(e);
        }
        
        logger.info("任务 "+jobName+" 触发时间:"+cronExpression);
        
        return cronTrigger;
    }
    
    /**
     * 删除job
     * @param jobName
     * @param jobGroup
     */
    public static void removeJob(String jobName,String jobGroup){
        
        logger.info("删除任务:jobName:"+jobName +" jobGroup:"+jobGroup);
        
        Scheduler scheduler = null;
        String[] jobNames = null;
        try {
            scheduler = getSchedulerFactory().getScheduler();
            jobNames = scheduler.getJobNames(jobGroup);
            if(jobNames==null||jobNames.length==0){
                return;
            }
            for(String name:jobNames){
                if(name.equals(jobName)){
                    scheduler.pauseTrigger(jobName, jobGroup);//停止触发器
                    scheduler.pauseJob(jobName, jobGroup);//暂停job
                    scheduler.unscheduleJob(jobName, jobGroup);//取消预订的job
                    scheduler.deleteJob(jobName, jobGroup);//删除job
                }
            }
            
        } catch (SchedulerException e) {
            logger.error(e);
        }
    }
    
    /**
     * 获取任务列表
     * @return
     */
    public static Map<String, List<String>> getJobList(){
        
        Scheduler scheduler = null;
        Map<String, List<String>> map = null;
        try {
            scheduler = getSchedulerFactory().getScheduler();
            
            String[] jobGroupNames = scheduler.getJobGroupNames();
            if(jobGroupNames==null||jobGroupNames.length==0){
                return null;
            }
            
            map = new HashMap<String, List<String>>();
            
            for(String jobGroup :jobGroupNames){
                
                String[] jobNames = scheduler.getJobNames(jobGroup);
                if(jobNames==null||jobNames.length==0){
                    continue;
                }
                
                List<String> jobNameList = new ArrayList<String>();
                
                for(String jobName : jobNames){
                    jobNameList.add(jobName);
                }
                
                map.put(jobGroup, jobNameList);
            }
            
        } catch (SchedulerException e) {
            logger.error(e);
        }
        
        logger.info("获取job列表:"+map);
        
        return map;
    }    
    
}

二、业务类

package com.tech.jin.job;

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

public class TestJob implements Job{

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        
        //可以context中获取到之前存入jobDataMap中的参数
        JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
        String value = (String)jobDataMap.get("key");
        
        System.out.println(value);
        
    }

}

三、调用

        Job job = new TestJob();
        Map<String, String> map = new HashMap<String, String>();
        map.put("key", "hello world");
        JobUtil.addJob(job, job.getClass().getName(), "0/10 * * * * ?", map);

 

posted @ 2017-06-12 15:06  bjlhx15  阅读(424)  评论(0编辑  收藏  举报
Copyright ©2011~2020 JD-李宏旭