任务调度框架Quartz学习笔记—概述及第一个例子

来源:互联网 发布:会java学python 编辑:程序博客网 时间:2024/05/18 02:47

Quartz是一个开源的作业调度框架,可以让程序任务在预定义的日期和时间运行(相当于定时器的功能)。Quartz可以用来创建简单或复杂的日程安排执行几十,几百,甚至是十万的作业数。

一、Quartz中的几个重要的概念(类、接口):

  • Job:是一个接口,只有一个方法void execute(JobExecutionContext context),开发者实现该接口定义运行任务,JobExecutionContext类提供了调度上下文的各种信息。Job运行时的信息保存在JobDataMap实例中
  • JobDetail:Quartz在每次执行Job时,都重新创建一个Job实例,所以它不直接接受一个Job的实例,相反它接收一个Job实现类,以便运行时通过newInstance()的反射机制实例化Job。因此需要通过一个类来描述Job的实现类及其它相关的静态信息,如Job名字、描述、关联监听器等信息,JobDetail承担了这一角色
  • Trigger:是一个类,描述触发Job执行的时间触发规则。主要有SimpleTrigger和CronTrigger这两个子类。当仅需触发一次或者以固定时间间隔周期执行,SimpleTrigger是最适合的选择;而CronTrigger则可以通过Cron表达式定义出各种复杂时间规则的调度方案:如每早晨9:00执行,周一、周三、周五下午5:00执行等
  • Calendar:org.quartz.Calendar和java.util.Calendar不同,它是一些日历特定时间点的集合(可以简单地将org.quartz.Calendar看作java.util.Calendar的集合——java.util.Calendar代表一个日历时间点,无特殊说明后面的Calendar即指org.quartz.Calendar)。一个Trigger可以和多个Calendar关联,以便排除或包含某些时间点。假设,我们安排每周星期一早上10:00执行任务,但是如果碰到法定的节日,任务则不执行,这时就需要在Trigger触发机制的基础上使用Calendar进行定点排除
  • Scheduler:代表一个Quartz的独立运行容器,Trigger和JobDetail可以注册到Scheduler中,两者在Scheduler中拥有各自的组及名称,组及名称是Scheduler查找定位容器中某一对象的依据,Trigger的组及名称必须唯一,JobDetail的组和名称也必须唯一(但可以和Trigger的组和名称相同,因为它们是不同类型的)。Scheduler定义了多个接口方法,允许外部通过组及名称访问和控制容器中Trigger和JobDetail

二、Quartz官网中的第一个例子(更新时间:2017-11-03):

第一步:导包(以Maven项目为例)

在pom.xml文件中加入以下代码:

        <dependency>            <groupId>org.quartz-scheduler</groupId>            <artifactId>quartz</artifactId>            <version>2.2.1</version>        </dependency>        <dependency>            <groupId>org.quartz-scheduler</groupId>            <artifactId>quartz-jobs</artifactId>            <version>2.2.1</version>        </dependency>

第二步:创建Scheduler任务调度容器并启动它

  // Grab the Scheduler instance from the Factory  Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();  // and start it off  scheduler.start();

第三步:创建一个类实现Job接口并且重写execute方法

public class MyJob implements org.quartz.Job{    public MyJob() {    }    public void execute(JobExecutionContext context) throws JobExecutionException {        System.err.println("Hello World!  MyJob is executing.");    }}

说明:具体要执行的任务写在重写的exectute方法里面

第四步:具体执行的任务类绑定到JobDetail上

  // define the job and tie it to our MyJob class  JobDetail job = newJob(MyJob.class)      .withIdentity("job1", "group1")      .build();

第五步:定义Trigger(即触发器,定义了任务在什么时候运行)

  // Trigger the job to run now, and then repeat every 40 seconds  Trigger trigger = newTrigger()      .withIdentity("trigger1", "group1")      .startNow()      .withSchedule(simpleSchedule()              .withIntervalInSeconds(40)              .repeatForever())      .build();

第六步:把JobDetail和Trigger绑定到Scheduler任务调度容器上

  // Tell quartz to schedule the job using our trigger  scheduler.scheduleJob(job, trigger);

完整的代码如下:

pom.xml文件:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelVersion>4.0.0</modelVersion>    <groupId>com.pl.quartz_demo</groupId>    <artifactId>quartz_demo</artifactId>    <version>0.0.1-SNAPSHOT</version>    <packaging>jar</packaging>    <name>quartz_demo</name>    <url>http://maven.apache.org</url>    <properties>        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>    </properties>    <dependencies>        <dependency>            <groupId>junit</groupId>            <artifactId>junit</artifactId>            <version>3.8.1</version>            <scope>test</scope>        </dependency>        <dependency>            <groupId>org.quartz-scheduler</groupId>            <artifactId>quartz</artifactId>            <version>2.2.1</version>        </dependency>        <dependency>            <groupId>org.quartz-scheduler</groupId>            <artifactId>quartz-jobs</artifactId>            <version>2.2.1</version>        </dependency>    </dependencies></project>

具体任务类:

public class MyJob implements org.quartz.Job{    public MyJob() {    }    public void execute(JobExecutionContext context) throws JobExecutionException {        System.err.println("Hello World!  MyJob is executing.");    }}

程序启动:

public class MyScheduler {    public static void main(String[] args) {        try {            // Grab the Scheduler instance from the Factory            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();            // and start it off            scheduler.start();            // define the job and tie it to our HelloJob class            JobDetail job = newJob(MyJob.class).withIdentity("job1", "group1").build();            // Trigger the job to run now, and then repeat every 40 seconds            Trigger trigger = newTrigger().withIdentity("trigger1", "group1").startNow()                    .withSchedule(simpleSchedule().withIntervalInSeconds(40).repeatForever()).build();            // Tell quartz to schedule the job using our trigger            scheduler.scheduleJob(job, trigger);            try {                Thread.sleep(600000);            } catch (InterruptedException e) {                e.printStackTrace();            }            scheduler.shutdown();        } catch (SchedulerException se) {            se.printStackTrace();        }    }}
阅读全文
0 0