Java定时任务调度工具详解之Quartz篇(中级)一:浅谈JobExecutionContext&JobDatai&浅谈Trigger

概要:OpenSymphony提供的强大的开源任务调度框架
官网:http://www.quartz-scheduler.org/

纯java实现,精细控制排程

特点:强大的调度功能 ,灵活的应用方式,分布式和集群能力

主要用到的设计模式:Builder模式,Factory模式,组件模式,链式写法

三个核心概念:调度器,任务,触发器

Java定时任务调度工具详解之Quartz篇(中级)一:浅谈JobExecutionContext&JobDatai&浅谈Trigger_第1张图片

重要组成:Job JobDetail JobBuilder JobStore
Trigger TriggerBuilder ThreadPool Scheduler

Calendar 一个Trigger可以和多个Calendar关联,以排除或包含某些时间点

监听器:JobListener TriggerListener SchedulerListener

一.第一个Quartz程序

Quartz使用:
准备工作—建立Maven项目工程
—引入Quartz jar包
任务:让任务每隔两秒钟打印一次helloworld

Java定时任务调度工具详解之Quartz篇(中级)一:浅谈JobExecutionContext&JobDatai&浅谈Trigger_第2张图片

Java定时任务调度工具详解之Quartz篇(中级)一:浅谈JobExecutionContext&JobDatai&浅谈Trigger_第3张图片

Java定时任务调度工具详解之Quartz篇(中级)一:浅谈JobExecutionContext&JobDatai&浅谈Trigger_第4张图片

打开链接http://mavenrepository.com

搜索quartz

Java定时任务调度工具详解之Quartz篇(中级)一:浅谈JobExecutionContext&JobDatai&浅谈Trigger_第5张图片

Java定时任务调度工具详解之Quartz篇(中级)一:浅谈JobExecutionContext&JobDatai&浅谈Trigger_第6张图片

Java定时任务调度工具详解之Quartz篇(中级)一:浅谈JobExecutionContext&JobDatai&浅谈Trigger_第7张图片

复制里面的内容,粘贴到项目中的pom.xml文件中dependencies下,保存


<dependency>
    <groupId>org.quartz-schedulergroupId>
    <artifactId>quartzartifactId>
    <version>2.2.3version>
dependency>

编辑器会自动下载Quartz相关架包

Java定时任务调度工具详解之Quartz篇(中级)一:浅谈JobExecutionContext&JobDatai&浅谈Trigger_第8张图片

我们也可以Maven Install

Java定时任务调度工具详解之Quartz篇(中级)一:浅谈JobExecutionContext&JobDatai&浅谈Trigger_第9张图片

代码示例:

HelloJob类:

package HelloQuartz.helloQuartz;

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

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

public class HelloJob implements Job{

    public void execute(JobExecutionContext arg0) throws JobExecutionException {
        //打印当前的执行时间,格式为2017-01-01 00:00:00
        Date date = new Date();
        SimpleDateFormat sf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("Current Exec Time Is :" + sf.format(date));
        //编写具体的业务逻辑
        System.out.println("Hello World!");
    }

}

HelloScheduler类

package HelloQuartz.helloQuartz;

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

import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

public class HelloScheduler {

    public static void main(String[] args) throws SchedulerException {
        // 创建一个JobDetail示例,将该示例与HelloJob Class绑定
        JobDetail jobDetail = JobBuilder.newJob(HelloJob.class)
                .withIdentity("myJob", "group1").build();
        // 创建一个Trigger实例,定义该job立即执行,并且每隔两秒钟重复执行一次,直到永远
        Trigger triger = TriggerBuilder.newTrigger()
                .withIdentity("myTrigger","group1")
                .startNow()
                .withSchedule(
                        SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInSeconds(2)
                        .repeatForever())
                .build();
        //创建Scheduler实例
        SchedulerFactory sfact = new StdSchedulerFactory();
        Scheduler scheduler = sfact.getScheduler();
        scheduler.start();
        Date date = new Date();
        SimpleDateFormat sf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("Current Exec Time Is :" + sf.format(date));
        scheduler.scheduleJob(jobDetail, triger);
    }
}

二.浅谈JobExecutionContext&JobDatai

JobExecutionContext是什么?
当Scheduler调用一个Job,就会将JobExecutionContext传递给Job的execute()方法;
Job能通过JobExecutionContext对象访问到Quartz运行时候的环境以及Job本身的明细数据

JobDataMap是什么?
在进行任务调度时,JobDataMap存储在JobExecutionContext中,非常方便获取
JobDataMap可以用来装载任何可序列化的数据对象,当job实例对象被执行时这些参数对象会传递给它。
JobDataMap实现了JDK的Map接口,并且添加了一些非常方便的方法用来存取基本数据类型。

获取JobDataMap的两种方式

第一种方式从Map中直接获取

代码示例:

HelloScheduler类

package HelloQuartz.helloQuartz;

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

import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

public class HelloScheduler {

    public static void main(String[] args) throws SchedulerException {
        // 创建一个JobDetail示例,将该示例与HelloJob Class绑定
        JobDetail jobDetail = JobBuilder.newJob(HelloJob.class).withIdentity("myJob", "group1")
                .usingJobData("message", "hello MyJob1").usingJobData("FloatJobValue", 3.14F).build();
        // 创建一个Trigger实例,定义该job立即执行,并且每隔两秒钟重复执行一次,直到永远
        Trigger triger = TriggerBuilder.newTrigger()
                .withIdentity("myTrigger", "group1")
                .usingJobData("message","hello myTrigger1")
                .usingJobData("DoubleTriggerValue",2.0D)
                .startNow()
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(2).repeatForever()).build();
        // 创建Scheduler实例
        SchedulerFactory sfact = new StdSchedulerFactory();
        Scheduler scheduler = sfact.getScheduler();
        scheduler.start();
        Date date = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("Current Exec Time Is :" + sf.format(date));
        scheduler.scheduleJob(jobDetail, triger);
    }
}

HelloJob类

package HelloQuartz.helloQuartz;

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

import javax.naming.Context;

import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.TriggerKey;

public class HelloJob implements Job {

    public void execute(JobExecutionContext context) throws JobExecutionException {
        // 打印当前的执行时间,格式为2017-01-01 0000:00
        Date date = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("Current Exec Time Is :" + sf.format(date));

        JobKey key = context.getJobDetail().getKey();
        System.out.println("My Job name and group are:" + key.getName() + ":" + key.getGroup());
        TriggerKey trkey = context.getTrigger().getKey();
        System.out.println("My Trigger name and group are:" + trkey.getName() + ":" + trkey.getGroup());
        JobDataMap dataMap = context.getJobDetail().getJobDataMap();
        JobDataMap tdataMap = context.getTrigger().getJobDataMap();
        String JobMsg = dataMap.getString("message");
        Float jobFloatValue = dataMap.getFloat("FloatJobValue");
        String triggerMsg = tdataMap.getString("message");
        Double triggerDoubleValue = tdataMap.getDouble("DoubleTriggerValue");
        System.out.println("JobMsg is :"+JobMsg);
        System.out.println("triggerMsg is :"+triggerMsg);
        System.out.println("jobFloatValue is :"+jobFloatValue);
        System.out.println("triggerDoubleValue is :"+triggerDoubleValue);
    }

}

第二种方式:Job实现类中添加setter方法对应JobDataMap的键值(Quartz框架默认的JobFactory实现类在初始化job示例对象时会自动地调用这些setter方法)

HelloJob类

package HelloQuartz.helloQuartz;

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

import javax.naming.Context;

import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.TriggerKey;

public class HelloJob implements Job {

    private String message;
    private Float FloatJobValue;
    private Double DoubleTriggerValue;

    /**
     * @return the message
     */
    public String getMessage() {
        return message;
    }

    /**
     * @param message the message to set
     */
    public void setMessage(String message) {
        this.message = message;
    }

    /**
     * @return the floatJobValue
     */
    public Float getFloatJobValue() {
        return FloatJobValue;
    }

    /**
     * @param floatJobValue the floatJobValue to set
     */
    public void setFloatJobValue(Float floatJobValue) {
        FloatJobValue = floatJobValue;
    }

    /**
     * @return the doubleTriggerValue
     */
    public Double getDoubleTriggerValue() {
        return DoubleTriggerValue;
    }

    /**
     * @param doubleTriggerValue the doubleTriggerValue to set
     */
    public void setDoubleTriggerValue(Double doubleTriggerValue) {
        DoubleTriggerValue = doubleTriggerValue;
    }

    public void execute(JobExecutionContext context) throws JobExecutionException {
        // 打印当前的执行时间,格式为2017-01-01 00:00:00
        Date date = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("Current Exec Time Is :" + sf.format(date));

        JobKey key = context.getJobDetail().getKey();
        System.out.println("My Job name and group are:" + key.getName() + ":" + key.getGroup());
        TriggerKey trkey = context.getTrigger().getKey();
        System.out.println("My Trigger name and group are:" + trkey.getName() + ":" + trkey.getGroup());
        JobDataMap dataMap = context.getMergedJobDataMap();//合并之后的dataMap

        System.out.println("msg is :"+message);
        System.out.println("jobFloatValue is :"+FloatJobValue);
        System.out.println("triggerDoubleValue is :"+DoubleTriggerValue);
    }

}

HelloScheduler类

package HelloQuartz.helloQuartz;

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

import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

public class HelloScheduler {

    public static void main(String[] args) throws SchedulerException {
        // 创建一个JobDetail示例,将该示例与HelloJob Class绑定
        JobDetail jobDetail = JobBuilder.newJob(HelloJob.class).withIdentity("myJob", "group1")
                .usingJobData("message", "hello MyJob1").usingJobData("FloatJobValue", 3.14F).build();
        // 创建一个Trigger实例,定义该job立即执行,并且每隔两秒钟重复执行一次,直到永远
        Trigger triger = TriggerBuilder.newTrigger()
                .withIdentity("myTrigger", "group1")
                .usingJobData("message","hello myTrigger1")
                .usingJobData("DoubleTriggerValue",2.0D)
                .startNow()
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(2).repeatForever()).build();
        // 创建Scheduler实例
        SchedulerFactory sfact = new StdSchedulerFactory();
        Scheduler scheduler = sfact.getScheduler();
        scheduler.start();
        Date date = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("Current Exec Time Is :" + sf.format(date));
        scheduler.scheduleJob(jobDetail, triger);
    }
}

三.浅谈Trigger

Trigger是什么?
Quartz中的触发器用来告诉调度程序作业什么时候触发。即Trigger对象是用来触发执行Job的。

Java定时任务调度工具详解之Quartz篇(中级)一:浅谈JobExecutionContext&JobDatai&浅谈Trigger_第10张图片

触发器通用属性:
JobKey:表示job实例的标识,触发器被触发时,该指定的job实例会执行。
StartTime:表示触发器的时间表首次被触发的时间。它的值的类型是Java.util.Date
EndTime:指定触发器的不再被触发的时间。它的值的类型是Java.util.Date。

HelloJob类

package HelloQuartz.helloQuartz;

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

import javax.naming.Context;

import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.Trigger;
import org.quartz.TriggerKey;

public class HelloJob implements Job {

    private String message;
    private Float FloatJobValue;
    private Double DoubleTriggerValue;

    /**
     * @return the message
     */
    public String getMessage() {
        return message;
    }

    /**
     * @param message the message to set
     */
    public void setMessage(String message) {
        this.message = message;
    }

    /**
     * @return the floatJobValue
     */
    public Float getFloatJobValue() {
        return FloatJobValue;
    }

    /**
     * @param floatJobValue the floatJobValue to set
     */
    public void setFloatJobValue(Float floatJobValue) {
        FloatJobValue = floatJobValue;
    }

    /**
     * @return the doubleTriggerValue
     */
    public Double getDoubleTriggerValue() {
        return DoubleTriggerValue;
    }

    /**
     * @param doubleTriggerValue the doubleTriggerValue to set
     */
    public void setDoubleTriggerValue(Double doubleTriggerValue) {
        DoubleTriggerValue = doubleTriggerValue;
    }

    public void execute(JobExecutionContext context) throws JobExecutionException {
        // 打印当前的执行时间,格式为2017-01-01 00:00:00
        Date date = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("Current Exec Time Is :" + sf.format(date));
        Trigger currentTrigger = context.getTrigger();
        System.out.println("Start Time is :" +currentTrigger.getStartTime());
        System.out.println("End Time is :"+currentTrigger.getEndTime());
        JobKey jobKey = currentTrigger.getJobKey();
        System.out.println("JobKey info ---"+"JobName:"+jobKey.getName()+"jobGroup:"+jobKey.getGroup());
    }

}

HelloScheduler类

package HelloQuartz.helloQuartz;

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

import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

public class HelloScheduler {

    public static void main(String[] args) throws SchedulerException {
        Date date = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("Current Exec Time Is :" + sf.format(date));

        // 创建一个JobDetail示例,将该示例与HelloJob Class绑定
        JobDetail jobDetail = JobBuilder.newJob(HelloJob.class).withIdentity("myJob").build();
        //获取距离当前时间3秒后的时间
        date.setTime(date.getTime()+3000);
        //获取距离当前时间6秒后的时间
        Date endDate = new Date();
        endDate.setTime(endDate.getTime()+6000);
        // 创建一个Trigger实例,定义该job立即执行,并且每隔两秒钟重复执行一次,直到永远
        Trigger triger = TriggerBuilder
                .newTrigger()
                .withIdentity("myTrigger", "group1")
                .startAt(date)
                .endAt(endDate)
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(2).repeatForever()).build();
        // 创建Scheduler实例
        SchedulerFactory sfact = new StdSchedulerFactory();
        Scheduler scheduler = sfact.getScheduler();
        scheduler.start();

        scheduler.scheduleJob(jobDetail, triger);
    }
}

你可能感兴趣的:(SSM到Spring,Boot)