• org.quartz-scheduler 动态添加自动任务


    1.添加pom.xml

    <dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.2.3</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz-jobs -->
    <dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz-jobs</artifactId>
    <version>2.2.3</version>
    </dependency>

    2.添加配置文件,或者不添加使用默认也行,默认线程池数量为10

    打开quartz的jar包,可以找到该配置  quartz.properties

    复制到资源目录下修改如下

    org.quartz.scheduler.instanceName: DemoQuartz
    org.quartz.scheduler.rmi.export: false
    org.quartz.scheduler.rmi.proxy: false
    org.quartz.scheduler.wrapJobExecutionInUserTransaction: false
    
    org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool
    #线程池数量
    org.quartz.threadPool.threadCount: 1
    org.quartz.threadPool.threadPriority: 5
    org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true
    
    org.quartz.jobStore.misfireThreshold: 60000
    
    org.quartz.jobStore.class: org.quartz.simpl.RAMJobStore


    3.编写job
    DemoJob.class,HelloJob.class
    实现接口 org.quartz.Job

    package com.yun.base.job;
    
    import java.util.Calendar;
    
    import org.quartz.Job;
    import org.quartz.JobExecutionContext;
    import org.quartz.JobExecutionException;
    import org.quartz.SchedulerException;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    public class HelloJob implements Job {
        
        private static final Logger LOGGER =  LoggerFactory.getLogger(HelloJob.class);
    
        @Override
        public void execute(JobExecutionContext context)
                throws JobExecutionException {
            try {
                LOGGER.info(context.getScheduler().getSchedulerName());
                String jobParam = (String) context.getJobDetail().getJobDataMap().get("jobParam");
                if (jobParam != null) {
                    LOGGER.info(jobParam.toString());
                }
                LOGGER.info(Integer.toString(Calendar.getInstance().get(Calendar.SECOND)));
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        }
    
    }

    4.编写任务管理工具类 JobSchedule

    package com.yun.util;
    
    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.SchedulerException;
    import org.quartz.SchedulerFactory;
    import org.quartz.Trigger;
    import org.quartz.TriggerBuilder;
    import org.quartz.TriggerKey;
    import org.quartz.impl.StdSchedulerFactory;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    public class JobSchedule {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(JobSchedule.class);
    
        private static SchedulerFactory gSchedulerFactory = new StdSchedulerFactory();
        private static String JOB_GROUP_NAME = "YUN_JOBGROUP_NAME";
        private static String TRIGGER_GROUP_NAME = "YUN_TRIGGERGROUP_NAME";
    
        private JobSchedule(){
            
        }
        
        /**
         * @Description: 添加一个定时任务,使用默认的任务组名,触发器名,触发器组名
         * 
         * @param jobName
         *            任务名
         * @param cls
         *            任务
         * @param cron
         *            时间设置,参考quartz说明文档
         * @throws SchedulerException
         * 
         */
        public static void addJob(String jobName, Class cls, String cron)
                throws SchedulerException {
            Scheduler sched = gSchedulerFactory.getScheduler();
    
            // 用于描叙Job实现类及其他的一些静态信息,构建一个作业实例
            JobDetail jobDetail = JobBuilder.newJob(cls)
                    .withIdentity(jobName, JOB_GROUP_NAME).build();
            
            // 构建一个触发器,规定触发的规则
            Trigger trigger = TriggerBuilder.newTrigger()// 创建一个新的TriggerBuilder来规范一个触发器
                    .withIdentity(jobName, TRIGGER_GROUP_NAME)// 给触发器起一个名字和组名
                    .startNow()// 立即执行
                    .withSchedule(CronScheduleBuilder.cronSchedule(cron)) // 触发器的执行时间
                    .build();// 产生触发器
    
            sched.scheduleJob(jobDetail, trigger);
            LOGGER.debug("添加任务:{},{},{}",jobName,cls,cron);
            // 启动
            if (!sched.isShutdown()) {
                sched.start();
            }
        }
    
        /**
         * @Description: 添加一个定时任务
         * 
         * @param jobName
         *            任务名
         * @param jobGroupName
         *            任务组名
         * @param triggerName
         *            触发器名
         * @param triggerGroupName
         *            触发器组名
         * @param jobClass
         *            任务
         * @param cron
         *            时间设置,参考quartz说明文档
         */
        public static void addJob(String jobName, String jobGroupName,
                String triggerName, String triggerGroupName, Class cls, String cron)
                throws SchedulerException {
    
            Scheduler sched = gSchedulerFactory.getScheduler();
            // 用于描叙Job实现类及其他的一些静态信息,构建一个作业实例
            JobDetail jobDetail = JobBuilder.newJob(cls)
                    .withIdentity(jobName, jobGroupName).build();
    
            // 构建一个触发器,规定触发的规则
            Trigger trigger = TriggerBuilder.newTrigger()// 创建一个新的TriggerBuilder来规范一个触发器
                    .withIdentity(jobName, triggerGroupName)// 给触发器起一个名字和组名
                    .startNow()// 立即执行
                    .withSchedule(CronScheduleBuilder.cronSchedule(cron)) // 触发器的执行时间
                    .build();// 产生触发器
    
            sched.scheduleJob(jobDetail, trigger);
            LOGGER.debug("添加任务:{},{},{},{},{},{}",jobName,jobGroupName,triggerName,triggerGroupName,cls,cron);
            // 启动
            if (!sched.isShutdown()) {
                sched.start();
            }
    
        }
    
        /**
         * @Description: 修改一个任务的触发时间(使用默认的任务组名,触发器名,触发器组名)
         * 
         * @param jobName
         * @param cron
         * @throws SchedulerException 
         * 
         */
        public static void modifyJobTime(String jobName, String cron) throws SchedulerException {
            Scheduler sched = gSchedulerFactory.getScheduler();
            TriggerKey triggerKey = new TriggerKey(jobName, TRIGGER_GROUP_NAME);
            CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerKey);
            if (trigger == null) {
                return;
            }
            String oldTime = trigger.getCronExpression();
            if (!oldTime.equalsIgnoreCase(cron)) {
                JobDetail jobDetail = sched.getJobDetail(new JobKey(jobName,
                        JOB_GROUP_NAME));
                Class objJobClass = jobDetail.getJobClass();
                removeJob(jobName);
                addJob(jobName, objJobClass, cron);
                LOGGER.debug("修改任务:{},{}",jobName,cron);
            }
        }
    
        /**
         * @Description: 移除一个任务(使用默认的任务组名,触发器名,触发器组名)
         * 
         * @param jobName
         * 
         * @throws SchedulerException
         */
        public static void removeJob(String jobName) throws SchedulerException {
            Scheduler sched = gSchedulerFactory.getScheduler();
    
            JobKey jobKey = new JobKey(jobName, TRIGGER_GROUP_NAME);
            // 停止触发器
            sched.pauseJob(jobKey);
            sched.unscheduleJob(new TriggerKey(jobName, TRIGGER_GROUP_NAME));// 移除触发器
            sched.deleteJob(jobKey);// 删除任务
            LOGGER.debug("移除任务:{}",jobName);
        }
    
        /**
         * 移除任务
         * 
         * @param jobName
         * @param jobGroupName
         * @param triggerName
         * @param triggerGroupName
         * @throws SchedulerException
         */
        public static void removeJob(String jobName, String jobGroupName,
                String triggerName, String triggerGroupName)
                throws SchedulerException {
            Scheduler sched = gSchedulerFactory.getScheduler();
            JobKey jobKey = new JobKey(jobName, jobGroupName);
            // 停止触发器
            sched.pauseJob(jobKey);
            sched.unscheduleJob(new TriggerKey(jobName, triggerGroupName));// 移除触发器
            sched.deleteJob(jobKey);// 删除任务
            LOGGER.debug("移除任务:{},{},{},{},{},{}",jobName,jobGroupName,triggerName,triggerGroupName);
        }
    
        /**
         * 启动所有任务
         * 
         * @throws SchedulerException
         */
        public static void startJobs() throws SchedulerException {
            Scheduler sched = gSchedulerFactory.getScheduler();
            sched.start();
            LOGGER.debug("启动所有任务");
        }
    
        /**
         * 关闭所有定时任务
         * 
         * @throws SchedulerException
         * 
         */
        public static void shutdownJobs() throws SchedulerException {
            Scheduler sched = gSchedulerFactory.getScheduler();
            if (!sched.isShutdown()) {
                sched.shutdown();
                LOGGER.debug("关闭所有任务");
            }
        }
    
    }

    5.测试 

      @Test
        public void testTask() {
             try {  
                 String job_name = "动态任务调度";  
                 System.out.println("【系统启动】开始(每1秒输出一次)...");    
                 JobSchedule.addJob(job_name, DemoJob.class, "0/1 * * * * ?");    
                   
                 Thread.sleep(5000);    
                 System.out.println("【修改时间】开始(每2秒输出一次)...");    
                 JobSchedule.modifyJobTime(job_name, "10/2 * * * * ?");    
                 Thread.sleep(6000);    
                 System.out.println("【移除定时】开始...");    
                 JobSchedule.removeJob(job_name);    
                 System.out.println("【移除定时】成功");    
                   
                 System.out.println("【再次添加定时任务】开始(每10秒输出一次)...");    
                 JobSchedule.addJob(job_name, HelloJob.class, "*/10 * * * * ?");    
                 Thread.sleep(60000);    
                 System.out.println("【移除定时】开始...");    
                 JobSchedule.removeJob(job_name);    
                 System.out.println("【移除定时】成功");  
             } catch (Exception e) {  
                 e.printStackTrace();  
             }  
        }

    测试结果

    【系统启动】开始(每1秒输出一次)...
    2017-07-20 18:11:03.026 [main] DEBUG com.yun.util.JobSchedule - 添加任务:动态任务调度,class com.yun.base.job.DemoJob,0/1 * * * * ?
    2017-07-20 18:11:03.042 [DemoQuartz_Worker-1] INFO  com.yun.base.job.DemoJob - DemoQuartz
    2017-07-20 18:11:03.042 [DemoQuartz_Worker-1] INFO  com.yun.base.job.DemoJob - 3
    2017-07-20 18:11:04.001 [DemoQuartz_Worker-1] INFO  com.yun.base.job.DemoJob - DemoQuartz
    2017-07-20 18:11:04.001 [DemoQuartz_Worker-1] INFO  com.yun.base.job.DemoJob - 4
    2017-07-20 18:11:05.004 [DemoQuartz_Worker-1] INFO  com.yun.base.job.DemoJob - DemoQuartz
    2017-07-20 18:11:05.004 [DemoQuartz_Worker-1] INFO  com.yun.base.job.DemoJob - 5
    2017-07-20 18:11:06.008 [DemoQuartz_Worker-1] INFO  com.yun.base.job.DemoJob - DemoQuartz
    2017-07-20 18:11:06.008 [DemoQuartz_Worker-1] INFO  com.yun.base.job.DemoJob - 6
    2017-07-20 18:11:07.012 [DemoQuartz_Worker-1] INFO  com.yun.base.job.DemoJob - DemoQuartz
    2017-07-20 18:11:07.012 [DemoQuartz_Worker-1] INFO  com.yun.base.job.DemoJob - 7
    2017-07-20 18:11:08.012 [DemoQuartz_Worker-1] INFO  com.yun.base.job.DemoJob - DemoQuartz
    2017-07-20 18:11:08.013 [DemoQuartz_Worker-1] INFO  com.yun.base.job.DemoJob - 8
    【修改时间】开始(每2秒输出一次)...
    2017-07-20 18:11:08.043 [main] DEBUG com.yun.util.JobSchedule - 移除任务:动态任务调度
    2017-07-20 18:11:08.047 [main] DEBUG com.yun.util.JobSchedule - 添加任务:动态任务调度,class com.yun.base.job.DemoJob,10/2 * * * * ?
    2017-07-20 18:11:08.047 [main] DEBUG com.yun.util.JobSchedule - 修改任务:动态任务调度,10/2 * * * * ?
    2017-07-20 18:11:10.001 [DemoQuartz_Worker-1] INFO  com.yun.base.job.DemoJob - DemoQuartz
    2017-07-20 18:11:10.001 [DemoQuartz_Worker-1] INFO  com.yun.base.job.DemoJob - 10
    2017-07-20 18:11:12.013 [DemoQuartz_Worker-1] INFO  com.yun.base.job.DemoJob - DemoQuartz
    2017-07-20 18:11:12.013 [DemoQuartz_Worker-1] INFO  com.yun.base.job.DemoJob - 12
    2017-07-20 18:11:14.005 [DemoQuartz_Worker-1] INFO  com.yun.base.job.DemoJob - DemoQuartz
    2017-07-20 18:11:14.005 [DemoQuartz_Worker-1] INFO  com.yun.base.job.DemoJob - 14
    【移除定时】开始...
    2017-07-20 18:11:14.054 [main] DEBUG com.yun.util.JobSchedule - 移除任务:动态任务调度
    【移除定时】成功
    【再次添加定时任务】开始(每10秒输出一次)...
    2017-07-20 18:11:14.054 [main] DEBUG com.yun.util.JobSchedule - 添加任务:动态任务调度,class com.yun.base.job.HelloJob,*/10 * * * * ?
    2017-07-20 18:11:20.010 [DemoQuartz_Worker-1] INFO  com.yun.base.job.HelloJob - DemoQuartz
    2017-07-20 18:11:20.010 [DemoQuartz_Worker-1] INFO  com.yun.base.job.HelloJob - 20
    2017-07-20 18:11:30.006 [DemoQuartz_Worker-1] INFO  com.yun.base.job.HelloJob - DemoQuartz
    2017-07-20 18:11:30.006 [DemoQuartz_Worker-1] INFO  com.yun.base.job.HelloJob - 30
    2017-07-20 18:11:40.004 [DemoQuartz_Worker-1] INFO  com.yun.base.job.HelloJob - DemoQuartz
    2017-07-20 18:11:40.005 [DemoQuartz_Worker-1] INFO  com.yun.base.job.HelloJob - 40
    2017-07-20 18:11:50.007 [DemoQuartz_Worker-1] INFO  com.yun.base.job.HelloJob - DemoQuartz
    2017-07-20 18:11:50.007 [DemoQuartz_Worker-1] INFO  com.yun.base.job.HelloJob - 50
    2017-07-20 18:12:00.010 [DemoQuartz_Worker-1] INFO  com.yun.base.job.HelloJob - DemoQuartz
    2017-07-20 18:12:00.010 [DemoQuartz_Worker-1] INFO  com.yun.base.job.HelloJob - 0
    2017-07-20 18:12:10.000 [DemoQuartz_Worker-1] INFO  com.yun.base.job.HelloJob - DemoQuartz
    2017-07-20 18:12:10.000 [DemoQuartz_Worker-1] INFO  com.yun.base.job.HelloJob - 10
    【移除定时】开始...
    2017-07-20 18:12:14.060 [main] DEBUG com.yun.util.JobSchedule - 移除任务:动态任务调度
    【移除定时】成功
  • 相关阅读:
    Javascript typeof 用法
    查询指定范围内数据记录(适用于sqlserver2005以上)
    提示信息并跳转的目标URL
    教你如何删除MSN群
    通过sqlserver2005 获取客户端信息
    分层遍历数据
    重写render,利用ClientScript,在客户端注册select,回发到服务器,触发服务器端的行选择事件。
    ASP.NET下的TreeView控件的使用(生成树与统计所有子节点数量)
    后台取浏览器中cookie的用法
    jdk开发环境的搭建
  • 原文地址:https://www.cnblogs.com/yun965861480/p/7211327.html
Copyright © 2020-2023  润新知