Construction and application of "Quartz" Quartz (using Quartz alone)

Source: Internet
Author: User

Read Catalogue

    • Excellent information for > reference
    • > Release Notes
    • > Easy to build
    • > Using quartz in Web applications
    • > Common cron Schedule

Quartz is a very common scheduling task framework in Java-built systems.

In this paper, we record and introduce the quartz of the simple introduction of the single building (this article is the primary learning quartz, not based on the spring hosted form).

Excellent information for > reference

Quartz Quick Start Guide

Chapter 3:logback Configuration

> Release Notes

In addition to Quartz, also introduced logback (in order to see the detailed log!) )

    <dependencies>        <dependency>            <groupId>org.quartz-scheduler</groupId>            < artifactid>quartz</artifactid>            <version>2.2.0</version>        </dependency>        <dependency>            <groupId>ch.qos.logback</groupId>            <artifactId>logback-classic< /artifactid>            <version>1.1.0</version>        </dependency>    </dependencies>

> Easy to build

The introduction of the jar package refers to the above Pom file.

Quartz.properties, configure the settings for Quartz.

note , Org.quartz.threadPool.threadCount, configures the capacity of the thread pool, which represents the maximum number of threads that can be run at the same time. In a production environment, this parameter should be configured according to the actual situation.

Org.quartz.scheduler.instanceName = MySchedulerorg.quartz.threadPool.threadCount = 3org.quartz.jobstore.class = Org.quartz.simpl.RAMJobStore

Logback.xml, the configuration of the log framework logback. This simply configures the output of the console and log files Oh (>_<)

<configuration>    <appender name= "STDOUT" class= "Ch.qos.logback.core.ConsoleAppender" >        <!-- Encoders is assigned the type Ch.qos.logback.classic.encoder.PatternLayoutEncoder by             Default-        < Encoder>            <pattern>%d{hh:mm:ss. SSS} [%thread]%-5level%logger{36}-%msg%n            </pattern>        </encoder>    </appender>    <appender name= "FILE" class= "Ch.qos.logback.core.FileAppender" >        <file>d:/logs/quartz_task_ application.log</file>        <encoder>            <pattern>%d{hh:mm:ss. SSS} [%thread]%-5level%logger{36}-%msg%n            </pattern>        </encoder>    </appender>    <root level= "Debug" >        <appender-ref ref= "STDOUT"/> <appender-ref        ref= "FILE"/>    </root></configuration>

Hellojob.java, specific tasks to be performed

Package No01 simple Scheduled tasks; Import Org.quartz.job;import Org.quartz.jobexecutioncontext;import Org.quartz.jobexecutionexception;import Org.slf4j.logger;import Org.slf4j.loggerfactory;public class HelloJob Implements Job {        Logger Logger = Loggerfactory.getlogger (This.getclass ());    @Override public    void execute (jobexecutioncontext arg0) throws Jobexecutionexception {        //This task prints only the logs for easy debugging, observation        This.logger.debug (This.getclass (). GetName () + "trigger ...");}    

So where do you define "when to perform what tasks?" ”

Package No01 simple Scheduled tasks; import Java.util.concurrent.timeunit;import Org.quartz.jobbuilder;import org.quartz.JobDetail; Import Org.quartz.scheduler;import Org.quartz.schedulerexception;import Org.quartz.simpleschedulebuilder;import Org.quartz.trigger;import Org.quartz.triggerbuilder;import Org.quartz.impl.stdschedulerfactory;import Org.slf4j.logger;import Org.slf4j.loggerfactory;public class Bootstrap {private static Logger Logger = LOGGERFACTORY.G    Etlogger (Bootstrap.class); public static void Main (string[] args) {try {//Get Scheduler instance Scheduler Scheduler = Stdsche            Dulerfactory.getdefaultscheduler ();            Scheduler.start ();            Specific tasks Jobdetail job = Jobbuilder.newjob (Hellojob.class). Withidentity ("Job1", "group1"). Build ();                    Trigger time point Simpleschedulebuilder Simpleschedulebuilder = Simpleschedulebuilder.simpleschedule ()            . Withintervalinseconds (5). RepeatForever (); Trigger Trigger = TriggErbuilder.newtrigger (). Withidentity ("Trigger1", "group1"). Startnow (). Withschedule (Simpleschedulebuilde            R). build ();                        By scheduler arrangement trigger scheduler.schedulejob (job, trigger);            /* Run for Watcher, this setting main program sleeps 3 minutes before continuing to run (because the next step is "Close scheduler") */try {TimeUnit.MINUTES.sleep (3);            } catch (Interruptedexception e) {e.printstacktrace ();        }//Close scheduler Scheduler.shutdown ();        } catch (Schedulerexception se) {logger.error (Se.getmessage (), SE); }    }}

> Using quartz in Web applications

Quartz is also commonly used in Web applications and is often referred to as a spring-hosted form, but this is not the case here. This article describes quartz for use in Web applications alone.

In general, when the Web application starts, it should register the scheduled tasks that have been determined, and some dynamic, indeterminate trigger time tasks, which can be registered by static scheduler.

This is where the listener registers with the app when it starts, remember to register the listener with Web. XML (>_<), and when you close the application, you also log off the timed task.

Other configuration files, Java classes are the same as in the example above, this is just the place to register timed tasks for this listener.

Package No02web applications use Quartz;import javax.servlet.servletcontextevent;import Javax.servlet.ServletContextListener; Import Org.quartz.jobbuilder;import Org.quartz.jobdetail;import Org.quartz.scheduler;import Org.quartz.schedulerexception;import Org.quartz.simpleschedulebuilder;import Org.quartz.Trigger;import Org.quartz.triggerbuilder;import Org.quartz.impl.stdschedulerfactory;import Org.slf4j.logger;import Org.slf4j.loggerfactory;import No01 Simple Scheduled task. hellojob;/** * Application Lifecycle Listener Implementation class Alistener * */public class Applicationcontextlistener implements Servletcontextlistener {private Logger Logger = L        Oggerfactory.getlogger (This.getclass ());    public static Scheduler Scheduler = null; @Override public void contextinitialized (Servletcontextevent arg0) {this.logger.info ("The Application start ...")                );          /* Register timed Task */try {//Get Scheduler Instance Scheduler = Stdschedulerfactory.getdefaultscheduler ();  Scheduler.start ();            Specific tasks Jobdetail job = Jobbuilder.newjob (Hellojob.class). Withidentity ("Job1", "group1"). Build ();                    Trigger time point Simpleschedulebuilder Simpleschedulebuilder = Simpleschedulebuilder.simpleschedule ()            . Withintervalinseconds (5). RepeatForever (); Trigger Trigger = Triggerbuilder.newtrigger (). Withidentity ("Trigger1", "group1"). Startnow (). withschedu            Le (Simpleschedulebuilder). build ();                        By scheduler arrangement trigger scheduler.schedulejob (job, trigger);        This.logger.info ("The Scheduler Register ...");        } catch (Schedulerexception se) {logger.error (Se.getmessage (), SE); }} @Override public void contextdestroyed (Servletcontextevent arg0) {this.logger.info ("the Applicati                On stop ... ");                        /* Unregister the Timer task */try {//Close scheduler Scheduler.shutdown (); This.logger.Info ("The Scheduler Shutdown ...");        } catch (Schedulerexception se) {logger.error (Se.getmessage (), SE); }    }}

    <listener>        <listener-class>no02web applications using quartz.applicationcontextlistener</listener-class>    </listener>

Note that if you debug in Eclipse, you may find that you cannot see the execution of the Contextdestroyed method, be careful to close the application using the Stop method (figure I) instead of terminate (figure II).

Figure A

Figure II

> Common cron Schedule

Compared to other ways to define timing task trigger time, we are more commonly used cron Schedule, small partners also?

Use of Cron Schedule

Specific tasks Jobdetail job = Jobbuilder.newjob (Hellojob.class). Withidentity ("Job1", "group1"). Build ();// Trigger time point Cronschedulebuilder Cronschedulebuilder = Cronschedulebuilder.cronschedule ("0 * * * *?") *"); Trigger Trigger = Triggerbuilder.newtrigger (). Withidentity ("Trigger1", "group1")        . Withschedule ( Cronschedulebuilder). Build ();//Scheduler Arrange trigger scheduler.schedulejob (job, trigger);

The learning of cron expression can be referred to the following excellent articles:

Tutorial-lesson 6:crontrigger

Question mark (?) in Spring-quartz-cronexpression The explanation

Construction and application of "Quartz" Quartz (using Quartz alone)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.