Quartz_2.2.X学习系列一:Tutorials - Lesson 1: Using Quartz

系列开篇前言:

Quartz_2.2.X学习系列,基本是将Quartz的官方文档Tutorials部分按段翻译成了中文,因为本人英语不太好,所以如果翻译得不恰当或有错误的地方,望大家指正。

希望对于不想看英文,但又想了解Quartz官方文档的朋友们有帮忙。

本系列将会分为以下几个部分:

1.学习Quartz的Tutorials作为入门,了解基本的概念

2.学习Quartz的官方例子,让基本的概念与实践结合起来。达到可以基本运用Quartz的目的。

3.学习Quartz的进阶知识,包含最佳实践,代码原理,项目应用等。

Quartz Tutorials

 

Quartz Job Scheduler Tutorials

Before starting the tutorial, you may first want to review the Quick Start Guide, which covers download, installation, and very basic configuration of Quartz.

Choose a Lesson:

Lesson 1: Using Quartz

Lesson 2: The Quartz API, and Introduction to Jobs And Triggers

Lesson 3: More About Jobs & JobDetails

Lesson 4: More About Triggers

Lesson 5: SimpleTriggers

Lesson 6: CronTriggers

Lesson 7: TriggerListeners & JobListeners

Lesson 8: SchedulerListeners

Lesson 9: JobStores

Lesson 10: Configuration, Resource Usage and SchedulerFactory

Lesson 11: Advanced (Enterprise) Features

Lesson 12: Miscellaneous Features

Choose a Special Topic:

CronTrigger Tutorial

 

From <http://www.quartz-scheduler.org/documentation/quartz-2.2.x/tutorials/>

 

第一课小结:本节举了一个简单的例子来说明,实现一个任务计划需要最基本的要素,

Schedule,我们需要实例化一个Schedule来调度任务,而是必须要启动。

Job,需要写一个Job类,用来实现这个任务具体要做什么事。需要继承Job类。

JobDetail , 用来定义Job,并需要绑定一个Job实现类,这样执行的时候,实际执行的是绑定的JOB类。

Trigger,定义一个Tigger,设定什么时间开始任务,什么时候结束

上面的元素都定义好后,需要通过Schedule将JobDetail与Trigger关联起来,实现在Trigger设定的时间来执行JobDetail绑定的Job

 

这样一个简单的计划任务就设定好了。

 

另:在构造Job, Trigger对象时,可以Import Quartz中的静态类,这样我们就可以直接使有使用Quartz中的静态方法。

import static org.quartz.JobBuilder.*;

JobDetail job = newJob(HelloJob.class)
      .withIdentity("myJob", "group1")
      .build();

 

 

Lesson 1: Using Quartz

Before you can use the scheduler, it needs to be instantiated (who’d have guessed?). To do this, you use a SchedulerFactory. Some users of Quartz may keep an instance of a factory in a JNDI store, others may find it just as easy (or easier) to instantiate and use a factory instance directly (such as in the example below).

Once a scheduler is instantiated, it can be started, placed in stand-by mode, and shutdown. Note that once a scheduler is shutdown, it cannot be restarted without being re-instantiated. Triggers do not fire (jobs do not execute) until the scheduler has been started, nor while it is in the paused state.

Here’s a quick snippet of code, that instantiates and starts a scheduler, and schedules a job for execution:

 

第一节:使用Quartz

在你可以使用scheduler 前,它需要被实例化。为了实现它,你可以使用SchedulerFactory。一些QUARTZ用户可以保持使用在JNDI仓库中工厂实例,另一些可能发现实例化和直接使用一个工厂实例很简单,或者说更简单。

如下面的例子就是使用这种方式。

 

当一个scheduler被实例化后,我们就可以把它开启,关闭。注意:一旦一个scheduler被关闭后,就需要重新实例化才可以再重新开启,否则不能开启。

 

在scheduler没有开启前,Triggers是不会触发的,它是处于暂停状态的。

 

下面有一小段代码,这段代码实例化和开启了一个Scheduler,然后安排了一个JOB执行。

 

SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory();

Scheduler sched = schedFact.getScheduler();

sched.start();

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

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

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

 

As you can see, working with quartz is rather simple. In Lesson 2 we’ll give a quick overview of Jobs and Triggers, and Quartz’s API so that you can more fully understand this example.

 

如同你看到的,用Quartz来工作是非常简单的。在第二节,我们将大致介绍一下JOBS,TRIGGERS和Quartz的API,让你可以更深入的理解这些例子。

 

Pasted from <http://www.quartz-scheduler.org/documentation/quartz-2.2.x/tutorials/tutorial-lesson-01.html>

Lab1.A simply quartz simple

-----------------------------------------------------------------------------------------------------------------------

package cn.ss.quartz.exam1;

 

import static org.quartz.DateBuilder.evenMinuteDate;

import static org.quartz.JobBuilder.newJob;

import static org.quartz.TriggerBuilder.newTrigger;

import static org.quartz.SimpleScheduleBuilder.simpleSchedule;

 

import org.quartz.JobDetail;

import org.quartz.Scheduler;

import org.quartz.SchedulerFactory;

import org.quartz.Trigger;

 

public class Lesson1 {

public static void main(String[] args) throws Exception {

 

SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory();

 

  Scheduler sched = schedFact.getScheduler();

 

  sched.start();

 

  // define the job and tie it to our HelloJob class

  JobDetail job = newJob(HelloJob.class)

      .withIdentity("myJob", "group1")

      .build();

 

  // Trigger the job to run now, and then every 40 seconds

  Trigger trigger = newTrigger()

      .withIdentity("myTrigger", "group1")

      .startNow()

      .withSchedule(simpleSchedule()

          .withIntervalInSeconds(5)

          .repeatForever())

      .build();

 

  // Tell quartz to schedule the job using our trigger

  sched.scheduleJob(job, trigger);

 

}

 

 

@Test

public void quartzTest1() throws SchedulerException, InterruptedException {

SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory();

 

Scheduler sched = schedFact.getScheduler();

 

sched.start();

 

// define the job and tie it to our HelloJob class

JobDetail job = newJob(HelloJob.class)//

.withIdentity("myJob", "group1")//

.build();

 

// Trigger the job to run now, and then every 40 seconds

Trigger trigger = newTrigger()

.withIdentity("myTrigger", "group1")//

.startNow()//

.withSchedule(simpleSchedule()//

.withIntervalInSeconds(5)//

.repeatForever())//

.build();

 

// Tell quartz to schedule the job using our trigger

sched.scheduleJob(job, trigger);

 

/**

 * if you use Junit to test,we need to add sleep to hold the time to excuete the schedule

 */

Thread.sleep(60000);

 

//shutdown the schedule

sched.shutdown();

}

 

}

-----------------------------------------------------------------------------------------------------------------------

2.This is just a simple job that says "Hello" to the world.

-----------------------------------------------------------------------------------------------------------------------

package cn.ss.quartz.exam1;

 

 

import java.util.Date;

 

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.quartz.Job;

import org.quartz.JobExecutionContext;

import org.quartz.JobExecutionException;

 

/**

 * <p>

 * This is just a simple job that says "Hello" to the world.

 * </p>

 *

 * @author Bill Kratzer

 */

public class HelloJob implements Job {

 

    private static Logger _log = LoggerFactory.getLogger(HelloJob.class);

 

    /**

     * <p>

     * Empty constructor for job initilization

     * </p>

     * <p>

     * Quartz requires a public empty constructor so that the

     * scheduler can instantiate the class whenever it needs.

     * </p>

     */

    public HelloJob() {

    }

 

    /**

     * <p>

     * Called by the <code>{@link org.quartz.Scheduler}</code> when a

     * <code>{@link org.quartz.Trigger}</code> fires that is associated with

     * the <code>Job</code>.

     * </p>

     *

     * @throws JobExecutionException

     *             if there is an exception while executing the job.

     */

    public void execute(JobExecutionContext context)

        throws JobExecutionException {

 

        // Say Hello to the World and display the date/time

            System.out.println("Hello World! - " + new Date());

        _log.info("Hello World! - " + new Date());

    }

 

}

-----------------------------------------------------------------------------------------------------------------------

Execute result:

信息: Scheduler MyScheduler_$_NON_CLUSTERED started.

2017-3-26 11:25:50 cn.ss.quartz.exam1.HelloJob execute

信息: Hello World! - Sun Mar 26 11:25:50 CST 2017

Hello World! - Sun Mar 26 11:25:50 CST 2017

2017-3-26 11:25:55 cn.ss.quartz.exam1.HelloJob execute

信息: Hello World! - Sun Mar 26 11:25:55 CST 2017

Hello World! - Sun Mar 26 11:25:55 CST 2017

The block of code that builds the job definition is using methods that were statically imported from the JobBuilder class. Likewise, the block of code that builds the trigger is using methods imported from the TriggerBuilder class - as well as from the SimpleScheduleBulder class.

The static imports of the DSL can be achieved through import statements such as these:

 

定义JOB的代码块是使用从JobBuilder类中导入的静态方法。同样的,构造trigger的代码块使用的方法是从TriggerBuilder类及SimpleScheduleBuilder中引用的方法。

DSL的静态引用可以通过import语句获取,示例如下:

----------------------------------------------------------------------------------------------------------------------

import static org.quartz.JobBuilder.*;

import static org.quartz.SimpleScheduleBuilder.*;

import static org.quartz.CronScheduleBuilder.*;

import static org.quartz.CalendarIntervalScheduleBuilder.*;

import static org.quartz.TriggerBuilder.*;

import static org.quartz.DateBuilder.*;

-----------------------------------------------------------------------------------------------------------------------

 

猜你喜欢

转载自blog.csdn.net/arnolian/article/details/82527910