溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

java 動態(tài)增加定時任務(wù)示例

發(fā)布時間:2020-09-22 21:19:34 來源:腳本之家 閱讀:172 作者:張錫斌 欄目:編程語言

整理文檔,java 動態(tài)增加定時任務(wù)示例,直接上代碼。

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: 定時任務(wù)管理類
 * 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: 添加一個定時任務(wù),使用默認的任務(wù)組名,觸發(fā)器名,觸發(fā)器組名
   *
   * @param jobName
   *      任務(wù)名
   * @param cls
   *      任務(wù)
   * @param time
   *      時間設(shè)置,參考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);// 任務(wù)名,任務(wù)組,任務(wù)執(zhí)行類
      jobDetail.getJobDataMap().put("params", params);
      // 觸發(fā)器
      CronTrigger trigger = new CronTrigger(jobName, TRIGGER_GROUP_NAME);// 觸發(fā)器名,觸發(fā)器組
      trigger.setCronExpression(time);// 觸發(fā)器時間設(shè)定
      sched.scheduleJob(jobDetail, trigger);
      // 啟動
      if (!sched.isShutdown()) {
        sched.start();
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * @Description: 添加一個定時任務(wù)
   *
   * @param jobName
   *      任務(wù)名
   * @param jobGroupName
   *      任務(wù)組名
   * @param triggerName
   *      觸發(fā)器名
   * @param triggerGroupName
   *      觸發(fā)器組名
   * @param jobClass
   *      任務(wù)
   * @param time
   *      時間設(shè)置,參考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);// 任務(wù)名,任務(wù)組,任務(wù)執(zhí)行類
      jobDetail.getJobDataMap().put("params",params);
      // 觸發(fā)器
      CronTrigger trigger = new CronTrigger(triggerName, triggerGroupName);// 觸發(fā)器名,觸發(fā)器組
      trigger.setCronExpression(time);// 觸發(fā)器時間設(shè)定
      sched.scheduleJob(jobDetail, trigger);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * @Description: 修改一個任務(wù)的觸發(fā)時間(使用默認的任務(wù)組名,觸發(fā)器名,觸發(fā)器組名)
   *
   * @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: 修改一個任務(wù)的觸發(fā)時間
   *
   */
  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);
        // 重啟觸發(fā)器
        sched.resumeTrigger(triggerName, triggerGroupName);
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * @Description: 移除一個任務(wù)(使用默認的任務(wù)組名,觸發(fā)器名,觸發(fā)器組名)
   *
   * @param jobName
   *
   */
  public static void removeJob(String jobName) {
    try {
      Scheduler sched = gSchedulerFactory.getScheduler();
      sched.pauseTrigger(jobName, TRIGGER_GROUP_NAME);// 停止觸發(fā)器
      sched.unscheduleJob(jobName, TRIGGER_GROUP_NAME);// 移除觸發(fā)器
      sched.deleteJob(jobName, JOB_GROUP_NAME);// 刪除任務(wù)
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * @Description: 移除一個任務(wù)
   *
   */
  public static void removeJob(String jobName, String jobGroupName,
                 String triggerName, String triggerGroupName) {
    try {
      Scheduler sched = gSchedulerFactory.getScheduler();
      sched.pauseTrigger(triggerName, triggerGroupName);// 停止觸發(fā)器
      sched.unscheduleJob(triggerName, triggerGroupName);// 移除觸發(fā)器
      sched.deleteJob(jobName, jobGroupName);// 刪除任務(wù)
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * @Description:啟動所有定時任務(wù)
   */
  public static void startJobs() {
    try {
      Scheduler sched = gSchedulerFactory.getScheduler();
      sched.start();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * @Description:關(guān)閉所有定時任務(wù)
   *
   */
  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: 任務(wù)執(zhí)行類
 * 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 = "動態(tài)任務(wù)調(diào)度";
      System.out.println("【系統(tǒng)啟動】開始(每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("【再次添加定時任務(wù)】開始(每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();
    }
  }
}

不過最后發(fā)現(xiàn),還是沒法做動態(tài)延遲。后面用延時mq實現(xiàn)的。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI