The most popular Java background frame Spring Quartz timed task _java

Source: Internet
Author: User

Configuration quartz requires three jar packages in spring:

Quartz-1.8.5.jar, Commons-collections-3.2.1.jar, Commons-logging-1.1.jar

First, we need to configure our Spring.xml

xmlns, add the following content,

xmlns:task= "Http://www.springframework.org/schema/task"

Then xsi:schemalocation add the following content,

Http://www.springframework.org/schema/task
Http://www.springframework.org/schema/task/spring-task-3.1.xsd

And finally, our task Tasks scan annotations

<task:annotation-driven/>

My configuration scan location is:

Copy Code code as follows:
<context:annotation-config/>
<bean class= "Org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<context:component-scan base-package= "Com.test"/>

Scanning is the contents of the package such as Com.test,

The following requires an interface and implementation (my Java files are all under the Com.test package)

Public interface Imytestservice {public 
    void myTest (); 
} 



@Component//import org.springframework.stereotype.Component; 
public class Mytestserviceimpl implements Imytestservice { 
   @Scheduled (cron= "0/5 * * * * *? ")  ///every 5 seconds 
   @Override public 
   void MyTest () { 
      System.out.println (" Enter Test "); 
   } 
 

After execution, the console prints out the entry test.

A few things to note:

1. Spring's @scheduled annotation needs to be written on implementation,

2, the task of the timer can not have a return value (if there is a return value, spring initialization will tell you that there is a mistake, you need to set a Proxytargetclass value is true, specific to Baidu Google bar)

3, implementation class to have components on the annotation @component

The rest is corn expression, specific use and parameters please Baidu Google,

"Seconds" "Minutes" "Days" "Month" "Week" "Year"

Here are just a few formulas

The meaning of cron expressions
"0 0 12 * *?" Every day at 12 o'clock noon trigger
"0 15 10?" * * "Every 10:15 trigger
"0 15 10 * *?" Triggers 10:15 every day.
"0 15 10 * *? * "Every 10:15 trigger
"0 15 10 * *? 2005 "2005 Every day 10:15 triggers
"0 * 14 * *?" Every day starting from 2 o'clock in the afternoon to 2:59 every minute of the trigger
"0 0/5 14 * *?" Every day from 2 o'clock in the afternoon to 2:55 to the end of every 5-minute trigger
"0 0/5 14,18 * *?" Triggers every 5 minutes from 2 o'clock in the afternoon to 2:55 and 6 to 6:55
"0 0-5 14 * *?" Triggers every day from 14:00 to 14:05 per minute
"0 10,44 14?" 3 WED "March of 14:10 and 14:44 triggers per Wednesday
"0 15 10?" * MON-FRI "10:15 triggers per Monday, Tuesday, Wednesday, Thursday, Friday

Sometimes our tasks (jobs) need to be completed before some tasks can be performed, such as when you bulk data from the old database, and you need to import data that is dependent on other data into the new database, and then import the relationship. In this case we can use quartz listener to make a fuss.

First we write a class of the main task, named Mainjob, and her role as a starting point for a series of tasks.

Mainjob.java

Package jobs;

Import Org.apache.log4j.Logger;
Import Org.quartz.JobExecutionContext;
Import org.quartz.JobExecutionException;
Import Org.springframework.scheduling.quartz.QuartzJobBean;

public class Mainjob extends Quartzjobbean {
private Logger Logger=logger.getlogger (GetClass ());
@Override
protected void executeinternal (Jobexecutioncontext arg0)
throws jobexecutionexception {
// TODO auto-generated Method Stub
logger.debug ("Just say hi.");
}



Then we create another task (Secondjob) as a successor:

Secondjob.java

Package jobs;

Import Org.apache.log4j.Logger;
Import Org.quartz.JobExecutionContext;
Import org.quartz.JobExecutionException;
Import Org.springframework.scheduling.quartz.QuartzJobBean;

public class Secondjob extends Quartzjobbean {
private Logger Logger=logger.getlogger (GetClass ());
@Override
protected void executeinternal (Jobexecutioncontext arg0)
throws jobexecutionexception {
// TODO auto-generated Method Stub
logger.debug ("I ' m the second job.");
}



Create a Triggerlistener, override its Triggercomplete method, and add some properties and methods that facilitate spring injection.

Nextjobtriggerlistener.java

Package listeners;
Import Org.apache.log4j.Logger;
Import Org.quartz.JobDetail;
Import Org.quartz.JobExecutionContext;
Import Org.quartz.Scheduler;
Import Org.quartz.Trigger;
Import Org.quartz.listeners.TriggerListenerSupport;
Import Org.springframework.scheduling.quartz.QuartzJobBean;

Import Org.springframework.scheduling.quartz.SimpleTriggerBean; public class Nextjobtriggerlistener extends Triggerlistenersupport {private Logger Logger=logger.getlogger (GetClass ()
);
private String name; Public String GetName () {return this.name.} public void SetName (String name) {this.name=name;} private Simpletriggerbe
an nexttrigger; public void Setnexttrigger (Simpletriggerbean nexttrigger) {This.nexttrigger=nexttrigger.} @Override public void Triggercomplete (Trigger Trigger, jobexecutioncontext context, int code) {try{Scheduler Schduler=context.getscheduler (
);
Jobdetail Nextjob=nexttrigger.getjobdetail (); Find names and tasks that are about to join Jobdetail Oldjob=schduler.getjobdetail (Nextjob.getname (), Nextjob. Getgroup ());

Find names and triggers that are about to be added Trigger Oldtrigger=schduler.gettrigger (Nexttrigger.getname (), Nexttrigger.getgroup ()); if (oldjob==null&&oldtrigger==null)//both tasks and triggers with the same name do not exist {Logger.debug ("inside schedulejob.")
+code);
Schduler.schedulejob (Nextjob,nexttrigger);
}else//task or Trigger {logger.debug ("Oldjob==null:" + (Oldjob==null)) with the same name;
Logger.debug ("Oldtrigger==null:" + (Oldtrigger==null));}
Super.triggercomplete (trigger, context, code);


}catch (Exception e) {e.printstacktrace ();}}

 }

Configure Spring's Applicationcontext.xml

Applicationcontext.xml

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:jee= "Http://www.springframework.org/schema/jee" xsi: Schemalocation= "http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/ Spring-beans-2.0.xsd Http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/ Spring-jee-2.0.xsd "> <!--main task--> <bean id=" Mainjob "class=" Org.springframework.scheduling.quartz.JobDetailBean "> <!--Run class--> <property name=" Jobclass "> < value> jobs. Mainjob </value> </property> </bean> <!--host Task listener--> <bean id= "Maintriggerlistener" Listeners. Nextjobtriggerlistener "> <!--next trigger--> <property name=" Nexttrigger "ref=" Secondtrigger "></ property> <!--listener name--> <property name= "name" value= "Maintriggerlistener" ></property> </bean > <!--main tasksTrigger--> <bean id= "Maintrigger" class= "Org.springframework.scheduling.quartz.SimpleTriggerBean" > < Property name= "Jobdetail" > <!--the task scheduling object created above--> <ref bean= "Mainjob"/> </property> <!--
Excute method to perform task scheduling after starting 60 seconds--> <property name= "Startdelay" > <value> 6000 </value> </property> <!--run times--> <property name= "RepeatCount" > <value> </value> </property> <!-- Run once every one hours (seemingly superfluous, do not write an error)--> <property name= "Repeatinterval" > <value> 3600000 </value> </ property> <property name= "Triggerlistenernames" > <list> <value> maintriggerlistener </value > </list> </property> </bean> <!--follow-on tasks--> <bean id= "Secondjob" class= " Org.springframework.scheduling.quartz.JobDetailBean "> <!--Run class--> <property name=" Jobclass "> < value> jobs. Secondjob </value> </property> </bean> <!--successor task triggers--> <bean id= "sEcondtrigger "class=" Org.springframework.scheduling.quartz.SimpleTriggerBean "> <property name=" Jobdetail " > <!--Task Scheduler created above--> <ref bean= "Secondjob"/> </property> <!--Excute method to perform task scheduling after 6 seconds--> < Property name= "Startdelay" > <value> 6000 </value> </property> <!--run times--> <property name = "RepeatCount" > <value> </value> </property> <!--run once every one hours (seemingly superfluous, do not write an error)--> <property Name= "Repeatinterval" > <!--<value>3600000</value>--> <value> 6000 </value> </ Property> </bean> <!--task Dispatch factory class--> <bean class= " Org.springframework.scheduling.quartz.SchedulerFactoryBean "> <!--this part of the configuration without--> <property name="
Quartzproperties "> <props> <prop key=" Org.quartz.threadPool.class ">
Org.quartz.simpl.SimpleThreadPool </prop> <prop key= "Org.quartz.threadPool.threadCount" > </prop> <prop key= "Org.quartz.threadPool.threadPrIority "> </prop> <prop key="
Org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread "> True </prop> </props> </property> <!--triggers, you can put a bunch of triggers--> <property name= "triggers" > <list> <!--add--> here <ref bean= "Maintrigger"/> </list> </property> <property name= "Triggerlisteners" > <list> <!-

 -Trigger listener--> <ref bean= "Maintriggerlistener"/> </list> </property> </bean> </beans>

Open Server, Output

DEBUG [mainjob.executeinternal] Just say hi.
Debug [Nextjobtriggerlistener.triggercomplete ()] inside schedulejob. 3
Debug [Secondjob.executeinternal (14)] I ' m the second job.
Debug [Nextjobtriggerlistener.triggercomplete ()] oldjob==null:false
Debug [ Nextjobtriggerlistener.triggercomplete ()] oldtrigger== Null:false

In addition, a task here only binds a simple trigger, in order to be able to easily detect the completion of the task, as to the specific content of the task to be played by everyone. Writing this article would like someone to get some inspiration.

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.