Quartz integration spring exercises

Source: Internet
Author: User

I did a quartz exercise some time ago and found that most of my recent studies were found on the Internet. Haha.

Quartz is a framework of scheduled tasks, similar to the job plan on the Windows platform and crontab on the Linux platform.

The following code is attached:

The first is a small example of quartz implemented by the Code:

The jar package used is described as follows:

Aopalliance-1.0.jar, aspectjweaver-1.5.3.jar, c3p0-0.9.1.1.jar, commons-logging-1.0.4.jar, jta-1.1.jar, log4j-1.2.14.jar,

Org. springframework. aop-3.1.0.RELEASE.jar, org. springframework. asm-3.1.0.RELEASE.jar, org. springframework. aspects-3.1.0.RELEASE.jar,

Org. springframework. beans-3.1.0.RELEASE.jar, org. springframework. Context. support-3.1.0.RELEASE.jar, org. springframework. context-3.1.0.RELEASE.jar,

Org. springframework. core-3.1.0.RELEASE.jar, org. springframework. expression-3.1.0.RELEASE.jar, org. springframework. jdbc-3.1.0.RELEASE.jar,

Org. springframework. transaction-3.1.0.RELEASE.jar, org. springframework. Web. struts-3.1.0.RELEASE.jar, org. springframework. web-3.1.0.RELEASE.jar,

Quartz-2.0.2.jar, quartz-all-2.0.2.jar, slf4j-api-1.6.1.jar, slf4j-log4j12-1.6.1.jar,

There are a few jar packages, some of which are redundant. You can check them! This is not cleared!

Note: In spring3.0, the built-in quartz version is <2.0. After the latest quartz package (> 2.0) is used, the interface is incompatible, causing an error in the program, in the quartz configuration file below, the solution is commented out.

Main function class. The testone method contains the method for creating a scheduled factory and executing the execution.

Package COM. zyujie. test; import Org. apache. log4j. logger; import Org. quartz. crontrigger; import Org. quartz. datebuilder; 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; public class simpleexample {Private Static logger = logger. getlogger (simpleexample. class); public static void main (string [] ARGs) {New simpleexample (). testone ();} private void testone () {try {// create a timer factory scheduler = stdschedulerfactory. getdefaschscheduler (); scheduler. start (); // start the timer // create a simple timer generator that generates the timer according to certain conditions, for example, simpleschedulebuilder schedbuilder = simpleschedulebuilder, a simple timer that is executed repeatedly at a specified interval. simpleschedule (). withintervalinseconds (1 ). repeatforever (); // create a trigger. datebuilder is responsible for creating complex tasks trigger = triggerbuilder. newtrigger (). withidentity ("trigger1", "group1 "). startat (datebuilder. nextgivenseconddate (null, 2 )). withschedule (schedbuilder ). build (); // create job details. The task to be executed must be Org. quartz. job interface jobdetail = jobbuilder. newjob (hellojob. class ). withidentity ("job1", "group1 "). build (); // get the timer // Add the job to the timer. You need to add jobdetail and triggerscheduler. schedulejob (jobdetail, trigger); // start the timer // scheduler. shutdown ();} catch (schedulerexception e) {e. printstacktrace () ;}}//// 1.1 create a jobdetail instance and specify simplejob // jobdetail jobdetail1 = jobbuilder. newjob (simplejob. class ). withidentity ("job1-1", "group1 "). build (); // 1.2 define scheduling rules through simpletrigger: start immediately, run once every 1 second, run 10 times in total // trigger simpletrigger1 = triggerbuilder. newtrigger (). withidentity ("trigger1", "group1 ")//. withschedule (simpleschedulebuilder. simpleschedule (). withintervalinseconds (1 ). withrepeatcount (10 )). startat (New Java. util. date ()). build (); // 2.1 create a jobdetail instance and specify simplejob // jobdetail jobdetail2 = jobbuilder. newjob (simplejob. class ). withidentity ("job1_2", "group1 "). build (); // 2.2 define scheduling rules through simpletrigger: start immediately, run once every 2 seconds, run three times in total // trigger simpletrigger2 = triggerbuilder. newtrigger (). withidentity ("trigger1_2", "group1 ")//. withschedule (simpleschedulebuilder. simpleschedule (). withintervalinseconds (2 ). withrepeatcount (3 )). startnow (). build (); // 3.0 get a scheduler instance through schedulerfactory // scheduler; // try {// scheduler = stdschedulerfactory. getdefaschscheduler (); // scheduler. schedulejob (jobdetail1, simpletrigger1); // register and schedule the job. // schedger. schedulejob (jobdetail2, simpletrigger2); // register and schedule the job. // schedger. start (); // scheduling start //} catch (schedulerexception e) {// E. printstacktrace ();//}

The following is the target class to be executed:

Package COM. zyujie. test; import Java. text. simpledateformat; import Org. apache. log4j. logger; import Org. quartz. job; import Org. quartz. jobexecutioncontext; import Org. quartz. jobexecutionexception; public class hellojob implements job {Private Static logger = logger. getlogger (hellojob. class); Public hellojob () {} public void execute (jobexecutioncontext arg0) throws jobexecutionexception {simpledateformat SDF = new simpledateformat ("yyyy-mm-dd hh: mm: SS "); system. out. println ("Print:" + SDF. format (New Java. util. date ()));}}

Execute the main method. Below is the spring Z integrated by spring. This usage should be practical and common:

The Web. xml configuration will not be written, that is, load the spring main configuration file. Due to the configuration in the project, the spring main configuration file is as follows:

<?xml version="1.0" encoding="utf-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"><!-- import products module  --><import resource="quartz-config.xml" /></beans>

The following is the quartz configuration file, which mainly configures the target class, target method, and triggering time:

<? XML version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: Jee = "http://www.springframework.org/schema/jee" xsi: schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsdhttp://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd"> <! -- The job class to be called --> <bean id = "quartzjob" class = "com. zyujie. Test. quartzjob"> </bean> <! -- Define the method for calling objects and calling objects --> <bean id = "jobtask" class = "org. springframework. Scheduling. Quartz. methodinvokingjobdetailfactorybean"> <! -- Called class --> <property name = "targetobject"> <ref bean = "quartzjob"/> </property> <! -- Call methods in the class --> <property name = "targetmethod"> <value> Work </value> </property> </bean> <! -- Define the trigger time --> <! -- <Bean id = "dotime" class = "org. springframework. Scheduling. Quartz. crontriggerbean"> --> <! -- In spring3.0, the built-in quartz version is <2.0. After using the latest quartz package (> 2.0), the interface is incompatible --> <! -- The solution is to reduce the Z version to 1.0 or add spring to 3.1 +. Based on Spring's suggestions, replace the original ** triggerbean with ** triggerfactorybean. For example, crontriggerbean can be replaced with crontriggerfactorybean. Solve the problem after replacement. --> <Bean id = "dotime" class = "org. springframework. scheduling. quartz. crontriggerfactorybean "> <property name =" jobdetail "> <ref bean =" jobtask "/> </property> <! -- Cron expression --> <property name = "cronexpression"> <! -- Execute the command once every 10 seconds --> <value> 0/10 ****? </Value> </property> </bean> <! -- If the general management class uses lazy-init = 'false', the container will execute the scheduler when it is started --> <bean id = "startquertz" lazy-init = "false" autowire = "No "Class =" org. springframework. scheduling. quartz. schedulerfactorybean "> <property name =" triggers "> <list> <ref bean =" dotime "/> </List> </property> </bean> </beans>

The following are the target classes and Methods configured in the quartz configuration file:

Package com. zyujie. Test; import java. Text. simpledateformat; public class quartzjob {public void work () {system. Out. println ("quartz Job Scheduling !!! "); Simpledateformat SDF = new simpledateformat (" yyyy-mm-dd hh: mm: SS "); system. out. println ("Print:" + SDF. format (New Java. util. date ()));}}

When the project is started, Web. xml loads the spring main configuration file to trigger the cron expression of quartz and execute the target class:

Execution result:

Quartz task scheduling !!!
Print: 18:07:40
Quartz task scheduling !!!
Print: 18:07:50

If you want to read the quartz configuration file separately, execute the methods in the target class. We can do this through applicationcontext:

Package COM. zyujie. test; import Org. springframework. context. applicationcontext; import Org. springframework. context. support. classpathxmlapplicationcontext; public class maintest {/*** @ Param ARGs */public static void main (string [] ARGs) {system. out. println ("Test start... "); applicationcontext context = new classpathxmlapplicationcontext (" quartz-config.xml "); // do not instantiate if the lazy-init of startquertz bean is set to false in the configuration file. getbean ("startquertz"); system. out. print ("test end... ");}}

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.