This is the 27th day of my participation in the August More Text Challenge

introduce

Quartz is another open source project in the field of Job Scheduling by the OpenSymphony organization. It is an open source task scheduling system developed entirely in Java. A system responsible for executing (or notifying) other software components. Quartz distributes files (.jar files) in a small Java library that contains all core Quartz functionality. The primary interface (API) for these functions is the Scheduler interface. It provides simple actions, such as putting tasks into or out of the schedule, and starting/stopping/pausing schedule progress.

Quartz core

  • Job executor. Users implement business logic
  • Jobdetail Indicates that a task is associated with a specific job
  • Trigger trigger, when does it execute
  • The Scheduler Scheduler

Common triggers include SimpleTrigger and CronTrigger

Job jobDetail

Each time Scheduler executes a Job, it obtains the corresponding Job, creates the Job instance, and executes execute() in the Job. After the Job execution is complete, the associated Job object instance is released. And will be cleared by the JVM GC.

Why not just say Job detail plus Job

The JobDetail defines the task data, while the real execution logic is in the Job. This is because tasks can be executed concurrently, and if the Scheduler uses the Job directly, there is the problem of concurrent access to the same Job instance. With JobDetail & Job, Sheduler creates a new Job instance based on JobDetail every time it executes, thus avoiding the problem of concurrent access.

JobExecutionContext The JobExecutionContext contains detailed data about the Quartz runtime environment and the Job itself. When a Job is executed by Schedule, the JobExecutionContext is passed to the Job’s execute(), and the Job gets information from the JobExecutionContext object.

Trigger

SimpleTrigger can execute a job once within a specified period of time or multiple times within a period of time.

CronTrigger is a very powerful calendar-based job scheduler, while SimpleTrigger is a precise interval, so CroTrigger is more commonly used than SimpleTrigger. CroTrigger is based on Cron expressions.

You can use the tool that generates Cron expressions online: cron.qqe2.com/ to generate your desired expressions.

Code instructions

Dependent jar

<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.3.0</version>
</dependency>
Copy the code

The use of Scheduler Scheduler

public class QuartzTest {
      public static void main(String[] args) {
          try {
              // Create a Scheduler from factory
              Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

              / / startscheduler.start(); ./ / close
              scheduler.shutdown();
          } catch(SchedulerException se) { se.printStackTrace(); }}}Copy the code

The use of JobDetail and Trigger

HelloJob Is a class that implements the job interface and processes the job of the user’s business logic

// define the job and tie it to our HelloJob class
  JobDetail job = newJob(HelloJob.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()
              / / between 40 s
              .withIntervalInSeconds(40)
              .repeatForever())            
      .build();

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

A complete example

package org.quartz.examples.example1;

import static org.quartz.DateBuilder.evenMinuteDate;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/** * This Example will demonstrate how to start and shutdown the Quartz scheduler and how to schedule a job to run in *  Quartz. * *@author Bill Kratzer
 */
public class SimpleExample {

  public void run(a) throws Exception {
    Logger log = LoggerFactory.getLogger(SimpleExample.class);

    log.info("------- Initializing ----------------------");

    // First we must get a reference to a scheduler
    SchedulerFactory sf = new StdSchedulerFactory();
    Scheduler sched = sf.getScheduler();

    log.info("------- Initialization Complete -----------");

    // computer a time that is on the next round minute
    Date runTime = evenMinuteDate(new Date());

    log.info("------- Scheduling Job -------------------");

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

    // Trigger the job to run on the next round minute
    Trigger trigger = newTrigger().withIdentity("trigger1"."group1").startAt(runTime).build();

    // Tell quartz to schedule the job using our trigger
    sched.scheduleJob(job, trigger);
    log.info(job.getKey() + " will run at: " + runTime);

    // Start up the scheduler (nothing can actually run until the
    // scheduler has been started)
    sched.start();

    log.info("------- Started Scheduler -----------------");

    // wait long enough so that the scheduler as an opportunity to
    // run the job!
    log.info("------- Waiting 65 seconds... -- -- -- -- -- -- -- -- -- -- -- -- --");
    try {
      // wait 65 seconds to show job
      Thread.sleep(65L * 1000L);
      // executing...
    } catch (Exception e) {
      //
    }

    // shut down the scheduler
    log.info("------- Shutting Down ---------------------");
    sched.shutdown(true);
    log.info("------- Shutdown Complete -----------------");
  }

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

    SimpleExample example = newSimpleExample(); example.run(); }}Copy the code
public class HelloJob implements Job {

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

    /** * 

* Empty constructor for job initilization *

*

* Quartz requires a public empty constructor so that the * scheduler can instantiate the class whenever it needs. *

*/
public HelloJob(a) {}/** * <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 _log.info("Hello World! -" + newDate()); }}Copy the code

conclusion

Quartz includes job, jobdetail, trigger, and Scheduler. The Scheduler is created by StdSchedulerFactory, and the Scheduler is associated with trigger and jobDetail. Trigger triggers the task and notifies the Scheduler to search jobDetail and create a job instance to execute user-defined service tasks.