• Quartz(任务调度)- 入门学习


     

    参照:http://blog.csdn.net/szwangdf/article/details/6158646

    1.自定义定时任务管理类 QuartzManager

    参照大神基础上
    新增:1.添加job时传入参数JobDataMap

       2.json和JobDataMap的互相转换

    import java.text.ParseException;
    import java.util.Iterator;
    
    import net.sf.json.JSONObject;
    
    import org.quartz.CronTrigger;
    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;
    
    
    /**
     * 定时任务管理类 
     * @author peak
     *
     */
    public class QuartzManager {  
        private static SchedulerFactory gSchedulerFactory = new StdSchedulerFactory();  
        private static String JOB_GROUP_NAME = "EXTJWEB_JOBGROUP_NAME";  
        private static String TRIGGER_GROUP_NAME = "EXTJWEB_TRIGGERGROUP_NAME";  
    
        
        /** 
         * 添加一个定时任务,使用默认的任务组名,触发器名,触发器组名 
         * 
         * @param jobName 
         *            任务名 
         * @param jobClass 
         *            任务 
         * @param time 
         *            时间设置,参考quartz说明文档 
         * @param jobDataMap 
         *            参数map
         * @throws SchedulerException 
         * @throws ParseException 
         */  
        public static void addJob(String jobName, String jobClass, String time,JobDataMap jobDataMap) {  
            try {  
                Scheduler sched = gSchedulerFactory.getScheduler();  
                JobDetail jobDetail = new JobDetail(jobName, JOB_GROUP_NAME, Class.forName(jobClass));// 任务名,任务组,任务执行类  
                if(jobDataMap!=null){
                    jobDetail.setJobDataMap(jobDataMap);
                }
                // 触发器  
                CronTrigger trigger = new CronTrigger(jobName, TRIGGER_GROUP_NAME);// 触发器名,触发器组  
                trigger.setCronExpression(time);// 触发器时间设定  
                sched.scheduleJob(jobDetail, trigger);  
                // 启动  
                if (!sched.isShutdown()){  
                    sched.start();  
                }  
            } catch (Exception e) {  
                e.printStackTrace();  
                throw new RuntimeException(e);  
            }  
        }  
    
        /** 
         * 添加一个定时任务 
         * 
         * @param jobName 
         *            任务名 
         * @param jobGroupName 
         *            任务组名 
         * @param triggerName 
         *            触发器名 
         * @param triggerGroupName 
         *            触发器组名 
         * @param jobClass 
         *            任务 
         * @param time 
         *            时间设置,参考quartz说明文档 
         * @throws SchedulerException 
         * @throws ParseException 
         */  
        public static void addJob(String jobName, String jobGroupName,  
                String triggerName, String triggerGroupName, String jobClass, String time,JobDataMap jobDataMap){  
            try {  
                Scheduler sched = gSchedulerFactory.getScheduler();  
                JobDetail jobDetail = new JobDetail(jobName, jobGroupName, Class.forName(jobClass));// 任务名,任务组,任务执行类  
                if(jobDataMap!=null){
                    jobDetail.setJobDataMap(jobDataMap);
                }
                // 触发器  
                CronTrigger trigger = new CronTrigger(triggerName, triggerGroupName);// 触发器名,触发器组  
                trigger.setCronExpression(time);// 触发器时间设定  
                sched.scheduleJob(jobDetail, trigger);  
            } catch (Exception e) {  
                e.printStackTrace();  
                throw new RuntimeException(e);  
            }  
        }  
    
        /** 
         * 修改一个任务的触发时间(使用默认的任务组名,触发器名,触发器组名) 
         * 
         * @param jobName 
         * @param time 
         */  
        public static void modifyJobTime(String jobName, String time,JobDataMap jobDataMap) {  
            try {  
                Scheduler sched = gSchedulerFactory.getScheduler();  
                CronTrigger trigger = (CronTrigger) sched.getTrigger(jobName, TRIGGER_GROUP_NAME);  
                if(trigger == null) {  
                    return;  
                }  
                String oldTime = trigger.getCronExpression();  
                if (!oldTime.equalsIgnoreCase(time)) {  
                    JobDetail jobDetail = sched.getJobDetail(jobName, JOB_GROUP_NAME);  
                    if(jobDataMap!=null){
                        jobDetail.setJobDataMap(jobDataMap);
                    }
                    Class objJobClass = jobDetail.getJobClass();  
                    String jobClass = objJobClass.getName();  
                    removeJob(jobName);  
    
                    addJob(jobName, jobClass, time,jobDataMap);  
                }  
            } catch (Exception e) {  
                e.printStackTrace();  
                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();  
                CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerName, triggerGroupName);  
                if(trigger == null) {  
                    return;  
                }  
                String oldTime = trigger.getCronExpression();  
                if (!oldTime.equalsIgnoreCase(time)) {  
                    CronTrigger ct = (CronTrigger) trigger;  
                    // 修改时间  
                    ct.setCronExpression(time);  
                    // 重启触发器  
                    sched.resumeTrigger(triggerName, triggerGroupName);  
                }  
            } catch (Exception e) {  
                e.printStackTrace();  
                throw new RuntimeException(e);  
            }  
        }  
    
        /** 
         * 移除一个任务(使用默认的任务组名,触发器名,触发器组名) 
         * 
         * @param jobName 
         */  
        public static void removeJob(String jobName) {  
            try {  
                Scheduler sched = gSchedulerFactory.getScheduler();  
                sched.pauseTrigger(jobName, TRIGGER_GROUP_NAME);// 停止触发器  
                sched.unscheduleJob(jobName, TRIGGER_GROUP_NAME);// 移除触发器  
                sched.deleteJob(jobName, JOB_GROUP_NAME);// 删除任务  
            } catch (Exception e) {  
                e.printStackTrace();  
                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();  
                sched.pauseTrigger(triggerName, triggerGroupName);// 停止触发器  
                sched.unscheduleJob(triggerName, triggerGroupName);// 移除触发器  
                sched.deleteJob(jobName, jobGroupName);// 删除任务  
            } catch (Exception e) {  
                e.printStackTrace();  
                throw new RuntimeException(e);  
            }  
        }  
    
        /** 
         * 启动所有定时任务 
         */  
        public static void startJobs() {  
            try {  
                Scheduler sched = gSchedulerFactory.getScheduler();  
                sched.start();  
            } catch (Exception e) {  
                e.printStackTrace();  
                throw new RuntimeException(e);  
            }  
        }  
    
        /** 
         * 关闭所有定时任务 
         */  
        public static void shutdownJobs() {  
            try {  
                Scheduler sched = gSchedulerFactory.getScheduler();  
                if(!sched.isShutdown()) {  
                    sched.shutdown();  
                }  
            } catch (Exception e) {  
                e.printStackTrace();  
                throw new RuntimeException(e);  
            }  
        }  
        
        
        /**
         * jobDataMap 转换为 json字符串
         * @param jobDataMap
         * @return
         */
        public static String jobDataMap2json(JobDataMap jobDataMap){
            String[] keys = jobDataMap.getKeys();
            JSONObject jsonObject = new JSONObject();
            for (int i = 0; i < keys.length; i++) {
                jsonObject.put(keys[i], jobDataMap.get(keys[i]));
            }
            return jsonObject.toString();
        }
        
        /**
         * json字符串 转换为 jobDataMap 
         * @param json
         * @return
         */
        public static JobDataMap json2jobDataMap(String json){
            JobDataMap jobDataMap = new JobDataMap();
            
            JSONObject jsonObject = JSONObject.fromObject(json);
            Iterator it = jsonObject.keys();  
            while (it.hasNext()) {  
                String key = (String) it.next();  
                String value = jsonObject.getString(key);
                jobDataMap.put(key, value);
            }
            
            return jobDataMap;
        }
        
    }

    2.简单使用

    添加任务(cron表达式)

    String job_name = "TestJob"+UUID.randomUUID();
    String job = "com.peak.TestJob";//全路径
    JobDataMap jobDataMap = new JobDataMap();
    jobDataMap.put("uuid",""+UUID.randomUUID());
    //cron表达式
    String cron = "*/5 * * * * ?";
    //简单的添加作业 
    QuartzManager.addJob(job_name, job, cron,jobDataMap); 

    任务(串行避免死锁)

    //具体任务类,实现了StatefulJob(单例,串行避免死锁),可实现Job接口(多例,并行)
    public class TestJob implements StatefulJob{
    
        //执行任务
        @Override
        public void execute(JobExecutionContext context) throws JobExecutionException {
    
                JobDetail jobDetail = context.getJobDetail();
                JobDataMap jobDataMap = jobDetail.getJobDataMap();
                //获取传入参数
                String uuid = jobDataMap.getString("uuid");
                //获取jobName
                String jobName = jobDetail.getName();
        }
    }
    作者:枫红一叶
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    asp.net 2.0 国际化 动态切换语言
    SKU、UPC、EAN和ISBN
    NCalc:处理数学运算的好帮手
    yaf 论坛安装
    Afterlogic xmail 邮局软件不能收email 设置
    要围着中心来做事
    保证Winform程序只有一个实例在运行
    可视热敏读写卡开发
    jQuery CSS 效果
    代碼小片斷
  • 原文地址:https://www.cnblogs.com/peak-c/p/5417621.html
Copyright © 2020-2023  润新知