Introduction and Getting Started with Task Scheduling Service Quartz

The Quartz framework is a full-featured, open source task scheduling service that can integrate almost any java application-from a small single-chip system to a large e-commerce system. Quartz can perform thousands of task scheduling. The Quartz scheduler contains many enterprise-level features, such as support for JTA transactions and clusters. (The simplest scheduler is a simple timer, how often it is executed) Quatrz can be regarded as an ordinary timing task. Only after Quartz encapsulation, more complex task scheduling can be completed. If your application has tasks that need to be performed at a specific time, or your system has regular maintenance tasks, then Quartz may be your ideal solution. Quartz can do the following applications:

  1. Provide notification services in the application.
  2. System maintenance: Provide a scheduler to dump the contents of the database to an XML file at 11:30 on every working day (all working days except holidays).
  3. Drive process workflow: When a new order is initially placed, a program is activated within two hours to check the status of the order, trigger a warning notification when the order confirmation message has not been received, and change the order status to "waiting for intervention".

Quartz provides a powerful operating environment and functions, which can almost meet any timing task or scheduling task used in the application. The following are the official features of Quartz:

Operating environment:

  1. Quartz can be embedded in another independent application to run.
  2. Quartz can be instantiated in the application server (or servlet container) and participate in XA transactions.
  3. Quartz can be run as a standalone program (in its own Java virtual machine) and can be used via RMI.
  4. Quartz can be instantiated as a set of independent programs (with load balancing and failover functions) for performing jobs.

Job scheduling:

The job is scheduled to run when a given trigger occurs. You can create triggers using almost any combination of the following commands:

  1. At a certain time of day (accurate to the millisecond)
  2. On certain days of the week
  3. On certain days of the month
  4. On certain days of the year
  5. Repeat a specific number of times
  6. Repeat until a specific date
  7. Keep repeating
  8. Execute every once in a while
  9. Specific dates that are not recorded in the calendar (such as business days)

Assignments are named by their creators and can be placed in a named group. Triggers can also be named and grouped so that they can be easily used in the scheduler. A job can be added to the scheduler once, but can be registered with multiple triggers. In an enterprise Java environment, jobs can perform their work as part of a distributed (XA) transaction.

Job execution:

  1. The job can be any Java class that implements the Job interface, leaving unlimited possibilities for the work that the job can perform.
  2. The job class instance can be instantiated by Quartz or the application framework, such as Spring.
  3. When the trigger is triggered, the scheduler notifies the existing Java objects that implement the JooListListor and TriggerListener interfaces (the listener can be a simple Java object, or EJB, or JMS publisher, etc.). These listeners will also be notified after the job is executed.
  4. When the job is completed, they return a job completion code (JobCompletionCode) to notify the scheduler of success or failure. The job completion code can also instruct the scheduler to take any actions based on the success/failure code, such as re-executing the job immediately.

Job persistence:

  1. Quartz's design includes a Jobstore interface, which can be implemented to provide various mechanisms for job storage.
  2. Using JDBCJobstore, all jobs and triggers configured as "non-volatile" ("non-volatile") are stored in a relational database through JDBC.
  3. Using RAMJobStore, all jobs and triggers are stored in RAM, so they will not persist between program executions, but this is the advantage of not requiring an external database

Affairs:

  1. Quartz can participate in JTA transactions through JobstoreCmt (a subclass of JDBCJobstore).
  2. Quartz can manage JTA transactions around the execution of jobs (start and submit them), so that the work performed by the job occurs automatically in the JTA transaction.

Cluster:

  1. Failover
  2. Load balancing
  3. Quartz's built-in cluster function relies on database persistence through JDBCJobstore (as described above).
  4. Terracotta extends Quartz's clustering capabilities without the need for a database to support it.

Listener and plugin:

  1. The application can capture scheduling events by implementing one or more listener interfaces to monitor or control job/trigger behavior
  2. Quartz comes with many "factory mode" plug-ins and listeners.
  3. The plug-in mechanism can be used to add functionality to Quartz, such as keeping a history of job execution, or loading job and trigger definitions from a file.

The use of Quartz is relatively simple. If it is a Maven project, we can directly import the corresponding jar file in pom.xml. In the example, I use Maven to import dependent files. When running the application or packaging the War package, I can directly package the dependencies in:

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

After importing the jar package needed by Quartz, we can create a simple Quartz program and run it. The following code obtains an instance of the scheduler, starts it, and then closes it. This process does not require any configuration files. The code is as follows:

public class QuzrtzTest {
    public static void main(String[] args) {
        try {
            // 从工厂中获取一个调度器
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            // 定义一个作业类,并且绑定到HelloJob类上
            JobDetail job = newJob(HelloJob.class).withIdentity("job1", "group1").build();
	    // 定义一个触发器,每隔10秒重复一次
	    Trigger trigger = newTrigger().withIdentity("trigger1", "group1").startNow()			.withSchedule(simpleSchedule().withIntervalInSeconds(10).repeatForever()).build();
	    // 告诉Quartz调度器启动我们使用我们定义的作业和触发器
	    scheduler.scheduleJob(job, trigger);
	    // 启动调度器
	    scheduler.start();
	    // 关闭调度器
	    scheduler.shutdown();
	} catch (SchedulerException se) {
			se.printStackTrace();
	}
    }
}

 

public class HelloJob implements Job {
    private static final Logger logger = LoggerFactory.getLogger(HelloJob.class);
    public void execute(JobExecutionContext context) throws JobExecutionException {
        logger.info("正在执行调度任务");
    }
}

Before calling shutdown(), you also need to allow some time to trigger and execute the job-for a simple example like this, you may only need to add a thread.sleep(60000) call.

Quartz can use a properties file named quartz.properties. You don't need to do this at the beginning, but to use other configurations than the most basic (default) configuration, you must put the configuration file in the classpath. Again, give an example based on my personal situation. My application is developed using WebLogic Workshop. I save all configuration files (including quartz.properties) in the project under the root directory of the application. When I packaged everything into an .ear file, the configuration project was packaged into a .jar, which was included in the final .ear. This will automatically put quartz.properties on the classpath.

If you are building a web application that includes Quartz (that is, in the form of a .war file), you may need to put the Quartz.properties file in the WEB-INF/classes folder so that it can be obtained on the classpath. This is the most important point! Quartz is a highly configurable application. The best way to configure quartz is to edit the quartz.properties file and place it in the classpath of the application.

There are several sample properties files in the Quartz distribution, especially under examples/directory. I suggest you create your own quartz.properties file instead of copying one of the examples and deleting the unnecessary parts. This method can make the quartz and properties files look cleaner, and you will find that Quartz provides more features. In order to get up and running quickly, the basic quartz.properties looks like this:

org.quartz.scheduler.instanceName = MyScheduler
org.quartz.threadPool.threadCount = 3
org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore

 

  1. org.quartz.scheduler.instanceName -  the name of this scheduler is "MyScheduler"
  2. org.quartz.threadPool.threadCount -  There are 3 threads in the thread pool, which means that up to 3 jobs can be run at the same time.
  3. org.quartz.jobStore.class  -  All Quartz data, such as job and trigger details, are stored in memory (not in the database). Even if you have a database and want to use it with Quartz, I suggest you first use RamJobStore to create Quartz applications, before you learn how to use a database to create Quartz programs.

Guess you like

Origin blog.csdn.net/wk19920726/article/details/108829203