一聚教程网:一个值得你收藏的教程网站

热门教程

java 动态增加定时任务示例

时间:2022-06-29 01:33:23 编辑:袖梨 来源:一聚教程网

整理文档,java 动态增加定时任务示例,直接上代码。

 

 代码如下复制代码

importorg.apache.tools.ant.util.DateUtils;

importorg.quartz.CronTrigger;

importorg.quartz.JobDetail;

importorg.quartz.Scheduler;

importorg.quartz.SchedulerFactory;

importorg.quartz.impl.StdSchedulerFactory;

 

importjava.util.Calendar;

importjava.util.Date;

 

 

/**

 * @Description: 定时任务管理类

 * Created by zhangxb on 2017/2/10.

 */

publicclassQuartzManager {

  privatestaticSchedulerFactory gSchedulerFactory =newStdSchedulerFactory();

  privatestaticString JOB_GROUP_NAME ="EXTJWEB_JOBGROUP_NAME";

  privatestaticString TRIGGER_GROUP_NAME ="EXTJWEB_TRIGGERGROUP_NAME";

 

  /**

   * @Description: 添加一个定时任务,使用默认的任务组名,触发器名,触发器组名

   *

   * @param jobName

   *      任务名

   * @param cls

   *      任务

   * @param time

   *      时间设置,参考quartz说明文档

   *

   * @Title: QuartzManager.java

   */

  @SuppressWarnings("unchecked")

  publicstaticvoidaddJob(String jobName, Class cls, String time,Object params) {

    try{

      Scheduler sched = gSchedulerFactory.getScheduler();

      JobDetail jobDetail =newJobDetail(jobName, JOB_GROUP_NAME, cls);// 任务名,任务组,任务执行类

      jobDetail.getJobDataMap().put("params", params);

      // 触发器

      CronTrigger trigger =newCronTrigger(jobName, TRIGGER_GROUP_NAME);// 触发器名,触发器组

      trigger.setCronExpression(time);// 触发器时间设定

      sched.scheduleJob(jobDetail, trigger);

      // 启动

      if(!sched.isShutdown()) {

        sched.start();

      }

    }catch(Exception e) {

      thrownewRuntimeException(e);

    }

  }

 

  /**

   * @Description: 添加一个定时任务

   *

   * @param jobName

   *      任务名

   * @param jobGroupName

   *      任务组名

   * @param triggerName

   *      触发器名

   * @param triggerGroupName

   *      触发器组名

   * @param jobClass

   *      任务

   * @param time

   *      时间设置,参考quartz说明文档

   *

   */

  @SuppressWarnings("unchecked")

  publicstaticvoidaddJob(String jobName, String jobGroupName,

               String triggerName, String triggerGroupName, Class jobClass,

               String time,Object params) {

    try{

      Scheduler sched = gSchedulerFactory.getScheduler();

      JobDetail jobDetail =newJobDetail(jobName, jobGroupName, jobClass);// 任务名,任务组,任务执行类

      jobDetail.getJobDataMap().put("params",params);

      // 触发器

      CronTrigger trigger =newCronTrigger(triggerName, triggerGroupName);// 触发器名,触发器组

      trigger.setCronExpression(time);// 触发器时间设定

      sched.scheduleJob(jobDetail, trigger);

    }catch(Exception e) {

      thrownewRuntimeException(e);

    }

  }

 

  /**

   * @Description: 修改一个任务的触发时间(使用默认的任务组名,触发器名,触发器组名)

   *

   * @param jobName

   * @param time

   *

   */

  @SuppressWarnings("unchecked")

  publicstaticvoidmodifyJobTime(String jobName, String time) {

    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);

        Class objJobClass = jobDetail.getJobClass();

        removeJob(jobName);

        addJob(jobName, objJobClass, time ,jobDetail.getJobDataMap());

      }

    }catch(Exception e) {

      thrownewRuntimeException(e);

    }

  }

 

  /**

   * @Description: 修改一个任务的触发时间

   *

   */

  publicstaticvoidmodifyJobTime(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) {

      thrownewRuntimeException(e);

    }

  }

 

  /**

   * @Description: 移除一个任务(使用默认的任务组名,触发器名,触发器组名)

   *

   * @param jobName

   *

   */

  publicstaticvoidremoveJob(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) {

      thrownewRuntimeException(e);

    }

  }

 

  /**

   * @Description: 移除一个任务

   *

   */

  publicstaticvoidremoveJob(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) {

      thrownewRuntimeException(e);

    }

  }

 

  /**

   * @Description:启动所有定时任务

   */

  publicstaticvoidstartJobs() {

    try{

      Scheduler sched = gSchedulerFactory.getScheduler();

      sched.start();

    }catch(Exception e) {

      thrownewRuntimeException(e);

    }

  }

 

  /**

   * @Description:关闭所有定时任务

   *

   */

  publicstaticvoidshutdownJobs() {

    try{

      Scheduler sched = gSchedulerFactory.getScheduler();

      if(!sched.isShutdown()) {

        sched.shutdown();

      }

    }catch(Exception e) {

      thrownewRuntimeException(e);

    }

  }

 

  publicstaticString formatTime(Date date){

    //0/1 * * * * ?

    String time = DateUtils.format( date,"s m h d * ?");

    System.out.println(time);

    returntime;

  }

}

 

测试类

 

 代码如下复制代码

importorg.quartz.Job;

importorg.quartz.JobExecutionContext;

importorg.quartz.JobExecutionException;

 

importjava.text.SimpleDateFormat;

importjava.util.Calendar;

importjava.util.Date;

 

/**

 * @Description: 任务执行类

 * Created by zhangxb on 2017/2/10.

 */

publicclassQuartzJobimplementsJob {

  @Override

  publicvoidexecute(JobExecutionContext context)throwsJobExecutionException {

    Object params =  context.getJobDetail().getJobDataMap().get("params");

    System.out.println(params);

    System.out.println(newSimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(newDate())+"★★★★★★★★★★★");

    System.out.println("【移除定时】开始...");

    QuartzManager.removeJob((String)params);

    System.out.println("【移除定时】成功");

  }

  publicstaticvoidmain(String[] args) {

    try{

      String job_name ="动态任务调度";

      System.out.println("【系统启动】开始(每1秒输出一次)...");

      Calendar cal = Calendar.getInstance();

      cal.add( Calendar.SECOND,10);

      QuartzManager.addJob(job_name, QuartzJob.class, QuartzManager.formatTime(cal.getTime()),job_name);

      Thread.sleep(11);

      cal.setTime(newDate());

      cal.add( Calendar.SECOND,10);

      QuartzManager.addJob(job_name+1, QuartzJob.class, QuartzManager.formatTime(cal.getTime()),job_name+1);

      Thread.sleep(11);

//      System.out.println("【修改时间】开始(每2秒输出一次)...");

//      QuartzManager.modifyJobTime(job_name, "10/2 * * * * ?");

//      Thread.sleep(6000);

//      System.out.println("【移除定时】开始...");

//      QuartzManager.removeJob(job_name);

//      System.out.println("【移除定时】成功");

//

//      System.out.println("【再次添加定时任务】开始(每10秒输出一次)...");

//      QuartzManager.addJob(job_name, QuartzJob.class, "*/10 * * * * ?");

//      Thread.sleep(60000);

//      System.out.println("【移除定时】开始...");

//      QuartzManager.removeJob(job_name);

//      System.out.println("【移除定时】成功");

    }catch(Exception e) {

      e.printStackTrace();

    }

  }

}

 

不过最后发现,还是没法做动态延迟。后面用延时mq实现的。

热门栏目