Simple construction of "Quartz" Quartz

Source: Internet
Author: User

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>
View Code

> 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
View Code

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

<Configuration>    <Appendername= "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>    <Appendername= "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-refref= "STDOUT" />        <Appender-refref= "FILE" />    </Root></Configuration>
View Code

Hellojob.java, specific tasks to be performed

 PackageNo01 simple Scheduled tasks;ImportOrg.quartz.Job;ImportOrg.quartz.JobExecutionContext;Importorg.quartz.JobExecutionException;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory; Public classHellojobImplementsJob {Logger Logger= Loggerfactory.getlogger ( This. GetClass ()); @Override Public voidExecute (jobexecutioncontext arg0)throwsjobexecutionexception {//This task prints only the logs for easy debugging, observation         This. Logger.debug ( This. GetClass (). GetName () + "trigger ..."); }}
View Code

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

 PackageNo01 simple Scheduled tasks;ImportJava.util.concurrent.TimeUnit;ImportOrg.quartz.JobBuilder;ImportOrg.quartz.JobDetail;ImportOrg.quartz.Scheduler;Importorg.quartz.SchedulerException;ImportOrg.quartz.SimpleScheduleBuilder;ImportOrg.quartz.Trigger;ImportOrg.quartz.TriggerBuilder;Importorg.quartz.impl.StdSchedulerFactory;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory; Public classBootstrap {Private StaticLogger Logger = Loggerfactory.getlogger (Bootstrap.class);  Public Static voidMain (string[] args) {Try {            //Get Scheduler InstanceScheduler Scheduler =Stdschedulerfactory.getdefaultscheduler ();            Scheduler.start (); //Specific TasksJobdetail job = Jobbuilder.newjob (hellojob.class). Withidentity ("Job1", "group1"). build (); //Trigger point in timeSimpleschedulebuilder Simpleschedulebuilder =simpleschedulebuilder.simpleschedule (). Withintervalinseconds (5). RepeatForever (); Trigger Trigger= Triggerbuilder.newtrigger (). Withidentity ("Trigger1", "group1"). Startnow (). Withschedule (Simpleschedulebuilder). build (); //Sent to Scheduler to arrange the triggerscheduler.schedulejob (Job, trigger); /*for the Watcher to run, this setting main program sleeps 3 minutes before continuing to run down (because the next step is "turn off scheduler")*/            Try{TimeUnit.MINUTES.sleep (3); } Catch(interruptedexception e) {e.printstacktrace (); }            //Close SchedulerScheduler.shutdown (); } Catch(schedulerexception se) {logger.error (Se.getmessage (), SE); }    }}
View Code

> 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.

 Packageno02web application using Quartz;Importjavax.servlet.ServletContextEvent;ImportJavax.servlet.ServletContextListener;ImportOrg.quartz.JobBuilder;ImportOrg.quartz.JobDetail;ImportOrg.quartz.Scheduler;Importorg.quartz.SchedulerException;ImportOrg.quartz.SimpleScheduleBuilder;ImportOrg.quartz.Trigger;ImportOrg.quartz.TriggerBuilder;Importorg.quartz.impl.StdSchedulerFactory;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;ImportNo01 Simple Scheduled Tasks. Hellojob;/*** Application Lifecycle Listener Implementation class Alistener **/ Public classApplicationcontextlistenerImplementsServletcontextlistener {PrivateLogger Logger = Loggerfactory.getlogger ( This. GetClass ());  Public StaticScheduler Scheduler =NULL; @Override Public voidcontextinitialized (servletcontextevent arg0) { This. Logger.info ("The Application start ..."); /*Registering timed Tasks*/        Try {            //Get Scheduler InstanceScheduler =Stdschedulerfactory.getdefaultscheduler ();            Scheduler.start (); //Specific TasksJobdetail job = Jobbuilder.newjob (hellojob.class). Withidentity ("Job1", "group1"). build (); //Trigger point in timeSimpleschedulebuilder Simpleschedulebuilder =simpleschedulebuilder.simpleschedule (). Withintervalinseconds (5). RepeatForever (); Trigger Trigger= Triggerbuilder.newtrigger (). Withidentity ("Trigger1", "group1"). Startnow (). Withschedule (Simpleschedulebuilder). build (); //Sent to Scheduler to arrange the triggerscheduler.schedulejob (Job, trigger);  This. Logger.info ("The Scheduler Register ..."); } Catch(schedulerexception se) {logger.error (Se.getmessage (), SE); }} @Override Public voidcontextdestroyed (servletcontextevent arg0) { This. Logger.info ("The Application Stop ..."); /*Unregister a scheduled task*/        Try {            //Close SchedulerScheduler.shutdown ();  This. Logger.info ("The Scheduler Shutdown ..."); } Catch(schedulerexception se) {logger.error (Se.getmessage (), SE); }    }}
View Code

    < Listener >        < Listener-class > No02web applications using Quartz.applicationcontextlistener</listener-class>     </listener>
View Code

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

"Quartz" Quartz Simple build

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.