欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java 动态增加定时任务示例

程序员文章站 2024-03-06 00:01:49
整理文档,java 动态增加定时任务示例,直接上代码。 import org.apache.tools.ant.util.dateutils; import...

整理文档,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实现的。

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