温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java 动态增加定时任务示例

发布时间:2020-09-22 21:19:34 来源:脚本之家 阅读:187 作者:张锡斌 栏目:编程语言

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

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实现的。

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI