SPRINGMVC Integrated Quartz implements timed tasks and spring self-task timed tasks

Source: Internet
Author: User
Tags tomcat server

In Java we use timer and timertask to implement timing functions, and spring can be used to integrate the quartz timer, spring task tasks in the Java EE project. Compared to spring's own task, quartz is very powerful, able to achieve all the desired timing tasks, including the start of the Tomcat server, scheduled fixed week, cluster timing tasks, and so on, the introduction of quartz and time configuration on the internet there are a lot of information, is not cumbersome, The following is a brief introduction to the implementation steps of SPRINGMVC integration Quartz.


SOURCE Blog: Http://blog.csdn.net/fengshizty


first, quartz scheduled Tasks


1. Introduction of Quartz

Import Quartz.jar packages, or pom.xml configuration corresponding dependencies:

                <dependency>
			<groupId>org.quartz-scheduler</groupId>
			<artifactid>quartz</ Artifactid>
			<version>1.8.6</version>
		

2, web.xml configuration

To configure the Quartz configuration file loading path in the Web project Web.xml:

        <servlet>
		<servlet-name>rest</servlet-name>
		<servlet-class> org.springframework.web.servlet.dispatcherservlet</servlet-class>
		<init-param>
			< param-name>contextconfiglocation</param-name>
			<param-value>
				/web-inf/classes/ Rest-servlet.xml, 
			   /web-inf/classes/pyc-spring-quartz.xml
			</param-value>
		</init-param> 
		<load-on-startup>1</load-on-startup>
	

3, write the specific timing of the task of scheduling:

Package andy.test.quartz.schedule;

/**  
 * @author zhang,tianyou  
 * @version: 2014-12-11 afternoon 12:00:24  
 * 
 *  a test print timed task
 * * Public

class Myprintschedule {public

	void printsomething () {
		//content is printed in a word
		System.out.println (" This is Andy Schedule ");
	}

 

4. Configure Quartz XML configuration information

Quartz configuration file name can be casually, need to be consistent with web.xml.

Pyc-spring-quartz.xml configuration information is as follows:


<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans/spring-beans-3.0.xsd > <!--Add scheduled task bean configuration corresponding Class--> <  Bean id= "Myprintschedule" class= "Andy.test.quartz.schedule.MyPrintSchedule"/> <!--the method of configuration scheduling is specifically implemented--> Id= "Myprintdetail" class= "Org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean" > < Property Name= "TargetObject" ref= "Myprintschedule"/> <property name= "Targetmethod" value= "printSomething"/ > <property name= "Concurrent" value= "false"/> </bean> <!--Configure scheduled execution time--> <bean id= "Myprint Trigger "class=" Org.springframework.scheduling.quartz.CronTriggerBean "> <property name=" jobdetail "ref=" Myprintdetail "/> <property name=" cronexpression "> <!--every morningPerform task scheduling on 8 points--> <value>0 0 8 * *?</value> </property> </bean> <!--Quartz Dispatch factory Dispatcher Factory can only have one, multiple scheduling tasks in the list add--> <bean class= "Org.springframework.scheduling.quartz.SchedulerFactoryBean" > <
				
			Property name= "Triggers" > <list> <!--all Schedule lists--> <ref local= "Myprinttrigger"/>  </list> </property> </bean> </beans>

This implements the Myprint task scheduling, which is performed every morning at 8 o ' time, printing:

This is Andy Schedule

This sentence.


The function of quartz is very powerful, the use is very simple and convenient, something needs to be done when the Web starts, perform some initialization tasks, this is the execution of our configuration corresponding to the execution of the trigger time can be completed. Its specific implementation is as follows:

<!--the time--> to configure scheduled execution
	<bean id= "Myprinttrigger" class= " Org.springframework.scheduling.quartz.CronTriggerBean ">
		<property name=" Jobdetail "ref=" Myprintdetail " />
		<property name= "Cronexpression" >
			<!--No repeat count, only once--> <property
			"Name=" "value=" 0 "/>
		</property>
	

The above configuration is complete, and the server initiates the execution of the task. is executed only once.


second, spring's own task tasks


Spring comes with a timed task that is supported after spring3, and is simpler to configure than the Quartz scheduled task spring. The quartz feature is more powerful than the spring task and supports cluster functionality.


1. Add a task schema to the spring configuration

Add namespaces and descriptions in the header of the Pring configuration file

<beans xmlns= "Http://www.springframework.org/schema/beans"
	xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance " 
	
	//.... Other
	
	xmlns:task= "Http://www.springframework.org/schema/task" 
	xsi:schemalocation= "
		http:// Www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-4.1.xsd 
		
		//..... Other
		
		Http://www.springframework.org/schema/task
		

2. Turn on the Scan Timing Task Pack


3, Configuration open Task


If more tasks are available, you can add task pools

<task:scheduler id= "Scheduler" pool-size= "5"/> <task:annotation-driven executor=
"executor" scheduler= "Scheduler"/>
    


4. Spring's Pojo task class

Package org.andy.task;

Import Org.apache.log4j.Logger;
Import org.springframework.scheduling.annotation.Scheduled;
Import org.springframework.stereotype.Component;

/**
 * Date: May 12, 2016 afternoon 3:48:38
 * * 
 @author Andy
 * @version 2.2
/@Component ("Taskjob") Public
class Taskjob {

	private static final Logger LOG = Logger.getlogger (taskjob.class);
	
	10-second execution @Scheduled per minute
	(cron = "* * * *?")
	public void Job1 () {
		log.info ("Hello .... "); 
	}
	
	Execute every 10 seconds
    @Scheduled (fixedrate = 1000 * 1) public 
	Void Job () {
    	log.info (' World ');
	}

 


Third, timing configuration

The task format for spring tasks and quartz is the same.

Cron expressions include the following 7 fields and the difference in order: seconds 0-59, Minutes 0-59, hour 0-23, month date 1-31, month 1-12 or JAN-DEC, week date 1-7 or Sun-sat, year (optional field) Leave blank or 1970-2099 and express special meaning by special characters, specifically: the slash (/) character represents the increment value.
    For example, in the second field, the "5/15" representation starts at 5th seconds, every 15 seconds. Question mark (?) The character and letter L characters are available only in the month and week date fields. The question mark indicates that the field does not contain a specific value. So, if you specify a date within the month, you can insert "?" in the Week Date field, which means that the date value in the week does not matter. Here is a very painful setting, not quartz, but spring integration quartz, it added a constraint, that is: the date (1-31) and the Week (SUN-SAT) both, must have a question mark (?). When the system starts, spring checks the expression, If it does not conform to its rules, it throws an exception.
    So it's important to be aware of this place when you're using it, and this is not the limit for implementing Cron on Linux. The letter L character is the abbreviation for last. Placed in the Month Date field, which is scheduled to be executed on the last day of the calendar. In the week Date field, if "L" exists alone, it equals "7", otherwise represents the last instance of the date within the week of the month.
    So "0L" is scheduled to be executed on the last Sunday of the month. The letter (W) character arranges execution to the working day closest to the specified value.
    Put "1W" in the Month Date field, indicating that the execution is scheduled within the first working day of the month. The pound sign (#) character specifies a specific weekday instance for a given month.
    Put "Mon#2" in the weekly Date field, indicating that the task is scheduled for the second Monday of the month.
    The asterisk (*) character is a wildcard character that indicates that the field can accept any possible values, an expression example. Example: "0 0 08 * *" Every day 8 o'clock in the morning trigger "0 15 10?" * * "0 15 10 * * *" every day 10:15 trigger "0 15 10 * *? * "0 15 10 * * per day 10:15 trigger"  2005 "2005 a Day 10:15 trigger" 0 * 14 * *? "1 0 0/5 minutes per 14 minute of every day from 2 o'clock in the afternoon to 2:59", triggering "5 0" in every 0/5 minutes of the Daily 2 o'clock in the afternoon to 2:55. 14-18 * *? "on a daily basisEvery 5 minutes from 2 o'clock in the afternoon to 2:55 and 6 o'clock in the afternoon to 6:55 trigger "0 0-5 14 * *" to trigger "1 10,44 0" in every 14 minutes of the Daily 2 o'clock in the afternoon to 2:05 period? 3 WED "Wednesday 2:10 and 2:44 triggers per year of March" 0 15 10? * Mon-fri "Monday to Friday 10:15 trigger" 0 15 10 15 *? "15th 10:15 every month" 0 L *? "10:15 trigger for the last day of the month 0 15 10? * 6L "The last Friday 10:15 trigger of the month" 0 15 10? * 6L 2009-2019 "2009 to 2019 month of the last Friday 10:15 trigger" 0 15 10? * 6#3 "The third Friday 10:15 trigger per month



SOURCE Blog: Http://blog.csdn.net/fengshizty



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.