189 8069 5689

java动态增加定时任务示例

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

创新互联制作网站网页找三站合一网站制作公司,专注于网页设计,网站制作、网站建设,网站设计,企业网站搭建,网站开发,建网站业务,680元做网站,已为上1000家服务,创新互联网站建设将一如既往的为我们的客户提供最优质的网站建设、网络营销推广服务!

import org.apache.tools.ant.util.DateUtils;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

import java.util.Calendar;
import java.util.Date;


/**
 * @Description: 定时任务管理类
 * Created by zhangxb on 2017/2/10.
 */
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";

  /**
   * @Description: 添加一个定时任务,使用默认的任务组名,触发器名,触发器组名
   *
   * @param jobName
   *      任务名
   * @param cls
   *      任务
   * @param time
   *      时间设置,参考quartz说明文档
   *
   * @Title: QuartzManager.java
   */
  @SuppressWarnings("unchecked")
  public static void addJob(String jobName, Class cls, String time,Object params) {
    try {
      Scheduler sched = gSchedulerFactory.getScheduler();
      JobDetail jobDetail = new JobDetail(jobName, JOB_GROUP_NAME, cls);// 任务名,任务组,任务执行类
      jobDetail.getJobDataMap().put("params", params);
      // 触发器
      CronTrigger trigger = new CronTrigger(jobName, TRIGGER_GROUP_NAME);// 触发器名,触发器组
      trigger.setCronExpression(time);// 触发器时间设定
      sched.scheduleJob(jobDetail, trigger);
      // 启动
      if (!sched.isShutdown()) {
        sched.start();
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * @Description: 添加一个定时任务
   *
   * @param jobName
   *      任务名
   * @param jobGroupName
   *      任务组名
   * @param triggerName
   *      触发器名
   * @param triggerGroupName
   *      触发器组名
   * @param jobClass
   *      任务
   * @param time
   *      时间设置,参考quartz说明文档
   *
   */
  @SuppressWarnings("unchecked")
  public static void addJob(String jobName, String jobGroupName,
               String triggerName, String triggerGroupName, Class jobClass,
               String time,Object params) {
    try {
      Scheduler sched = gSchedulerFactory.getScheduler();
      JobDetail jobDetail = new JobDetail(jobName, jobGroupName, jobClass);// 任务名,任务组,任务执行类
      jobDetail.getJobDataMap().put("params",params);
      // 触发器
      CronTrigger trigger = new CronTrigger(triggerName, triggerGroupName);// 触发器名,触发器组
      trigger.setCronExpression(time);// 触发器时间设定
      sched.scheduleJob(jobDetail, trigger);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * @Description: 修改一个任务的触发时间(使用默认的任务组名,触发器名,触发器组名)
   *
   * @param jobName
   * @param time
   *
   */
  @SuppressWarnings("unchecked")
  public static void modifyJobTime(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) {
      throw new RuntimeException(e);
    }
  }

  /**
   * @Description: 修改一个任务的触发时间
   *
   */
  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) {
      throw new RuntimeException(e);
    }
  }

  /**
   * @Description: 移除一个任务(使用默认的任务组名,触发器名,触发器组名)
   *
   * @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) {
      throw new RuntimeException(e);
    }
  }

  /**
   * @Description: 移除一个任务
   *
   */
  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) {
      throw new RuntimeException(e);
    }
  }

  /**
   * @Description:启动所有定时任务
   */
  public static void startJobs() {
    try {
      Scheduler sched = gSchedulerFactory.getScheduler();
      sched.start();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * @Description:关闭所有定时任务
   *
   */
  public static void shutdownJobs() {
    try {
      Scheduler sched = gSchedulerFactory.getScheduler();
      if (!sched.isShutdown()) {
        sched.shutdown();
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  public static String formatTime(Date date){
    //0/1 * * * * ?
    String time = DateUtils.format( date, "s m h d * ?");
    System.out.println(time);
    return time;
  }
}

测试类

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

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @Description: 任务执行类
 * Created by zhangxb on 2017/2/10.
 */
public class QuartzJob implements Job {
  @Override
  public void execute(JobExecutionContext context) throws JobExecutionException {
    Object params =  context.getJobDetail().getJobDataMap().get("params");
    System.out.println(params);
    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+ "★★★★★★★★★★★");
    System.out.println("【移除定时】开始...");
    QuartzManager.removeJob((String)params);
    System.out.println("【移除定时】成功");
  }
  public static void main(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( new Date());
      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实现的。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。


文章名称:java动态增加定时任务示例
网址分享:http://cdxtjz.com/article/jioioi.html

其他资讯