Job description in Java and the configuration of job in spring

Source: Internet
Author: User

2013-09-05 15:30:54| Category: Default Category | report | font size Subscription
1 Function of the timer
In the actual development, if the project needs to be timed or needs to be repeated to perform certain work, the timer appears particularly important.
Of course, if we do not understand the timer will be used to implement the thread, for example:
Package Org.lzstone.action
public class Financeaction extends thread{
private date date;
public void run{
try{
while (true) {
Thread.Sleep ((int) (Math.random () *1000));
Date = new Date ();
Perform tasks on a timed basis
}
}catch (Exception e) {
E.printstacktrace ();
}
}
}
The implementation of their own timer is very complex, if the implementation is not enough to take up too much memory, the system over, so to handle timed execution or repetitive tasks, the timer is a good choice
Common timers in the 2.java
1) using Java.util.Timer to achieve
2) Opensymphony community-provided quartz to achieve
3. Introducing the Timer
Using a timer to develop a timed task is mainly divided into two steps:
1) Create a timed task class
Example code:
Package Org.lzstone.action
Import Java.util.TimeTask
public class Lzstonetimetask extends timetask{
public void Run () {
Timer tasks to perform
}
}
2) Run timed tasks and run scheduled tasks in two ways:
2.1) program starts directly
Example code:
Package Org.lzstone.action
public class lzstonemain{
.......
public void Run () {
Tasks for performing timers
Create an instance
Timer timer = new timer ();
Parameters:
New Lzstonetimetask ()-the task to be scheduled.
0-The delay time, in milliseconds, before the task is performed.
1*1000-the time interval between successive tasks, in milliseconds.
Timer.schedule (New Lzstonetimetask (), 0,1*1000);
}
}
2.2) Web listening mode
Example code:
Package Org.lzstone.action
public class Lzstonemain implements servletcontextlistener{
Private timer timer = null;
Initialize listeners, create instances, perform tasks
public void contextinitialized (Servletcontextevent event) {
Timer = new timer ();
Timer.schedule (New Lzstonetimetask (), 0,1*1000);
}
Destroy the listener and stop performing the task
public void contextdestroyed (Servletcontextevent event) {
Note that this method is called within the Run method of the timer task called by this timer, and you can absolutely ensure that the task being performed is the last task that this timer performs.
Timer.cancel ();
}
}
Web. XML configuration
<listener>
<listener-class>
Org.lzstone.action.LzstoneMain
</listener-class>
</listener>
4. Introduction Quartz
Quartz is a opensymphony open source organization in the Job scheduling field another open-source project, can be used to create simple or complex scheduled tasks, the use of quartz to develop timed tasks and the timer class

Like.

The development of timed tasks using quartz is mainly divided into two steps:
1) Create a timed task class
Example code:
Package Org.lzstone.action
public class Lzstonetimetask implements job{
public void execute (jobexecutioncontext context) throws jobexecutionexception{
Timer tasks to perform
}
}
2) Run timed tasks and run scheduled tasks in two ways:
2.1) program launch directly, create Task Scheduler and configure the corresponding Task Scheduler
Example code:
Package Org.lzstone.action
public class lzstonemain{
private static Scheduler sched;
public static void Run () throws exception{
Create a timed task for Lzstonetimetask
Jobdetail jobdetail = new Jobdetail ("Lzstonejob", Sched. Default_group,lzstonetimetask.class);
Target Create task Schedule
Crontrigger trigger = new Crontrigger ("Lzstonetrigger", "Lzstone", "0 0 12 * *?");
0 0 12 * *? Represents a daily 12 o'clock noon trigger
Sched = new Org.quartz.impl.StdSchedulerFactory (). Getscheduler ();
Sched.schedulejob (Jobdetail,trigger);
Sched.start ();
}
Stop it
public static void Stop () throws exception{
Sched.shutdown ();
}
}
Perform
public class main{
.............
public void Run () {
Lzstonemain.run ();
}
............
}
2.2) Web listening mode
Example code:
Package Org.lzstone.action
public class Lzstonemainlistener implements servletcontextlistener{
Private timer timer = null;
Initialize listeners, create instances, perform tasks
public void contextinitialized (Servletcontextevent event) {
Lzstonemain.run ();
}
Destroy the listener and stop performing the task
public void contextdestroyed (Servletcontextevent event) {
Lzstonemain.stop ();
}
}
Web. XML configuration
<listener>
<listener-class>
Org.lzstone.action.LzstoneMainListener
</listener-class>
</listener>
5. Contrast
Timer way to implement timers, the principle of simple, easy to implement, in the implementation of simple tasks more convenient, the shortcomings are unable to determine the execution time, and the dependency is relatively strong, must inherit the specified class
Quartz Mode realization Timer, convenient, clearly specify the start time, timing parameters more flexible, easy to achieve more complex timing tasks, the disadvantage is the need to implement a specific interface, load its framework
Each of the two approaches has advantages and disadvantages, and can be used according to their characteristics in specific situations.
6.Spring Scheduled Tasks
Spring timed tasks support both the timer and the quartz, and the implementation steps are basically the same
First configure spring's support for the timer
1.1 Creating a Timed task class
Package Org.lzstone.action
Import Java.util.TimeTask
public class Lzstonetimetask extends timetask{
public void Run () {
Timer tasks to perform
}
}
1.2 Registering a Scheduled task class, configuring Task Scheduler and Task Scheduler
Create a Timerconfig.xml file under the project's Web-inf
<?xml version= "1.0" encoding= "UTF-8"?>
<! DOCTYPE beans Public "-//spring//dtd bean//en" "Http://www.springframework.org/dtd/spring-beans.dtd" >
<beans>
<bean>
<!--register timed task entity--
<bean id= "Lzstonetimetask" class= "Org.lzstone.action.LzstoneTimeTask"/>
<!--register Timer information--
<bean id= "TaskInfo" class= "Org.springframework.scheduling.timer.ScheduledTimerTask" >
<!--the time to wait before performing the first task, set here to 3 seconds--
<property name= "Delay" >
<value>3000</value>
</property>
<!--set the execution period of the task here to 4 seconds--
<property name= "Period" >
<value>4000</value>
</property>
<!--set specific tasks to perform here set to Lzstonetimetask-->
<property name= "TimerTask" >
<ref local= "Lzstonetimetask"/>
</property>
</bean>
<!--Scheduler to configure Timer tasks--
<bean id= "Timerfactory" class= "Org.springframework.scheduling.timer.TimerFactoryBean" >
<!--register a timer list--
<property name= "Scheduledtimertasks" >
<list>
<ref local= "TaskInfo"/>
........
</list>
</property>
</bean>
</beans>
1.3 Startup settings in a Web project
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/TimerConfig.xml</param-value>
</context-param>

<listener>
<listener-class>
Org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
Configuring Spring support for Quartz
2.1 Creating a Timed task class
Package Org.lzstone.action
public class lzstonequartztask{
public void execute () {
Timer tasks to perform
}
}
2.2 Registering a scheduled task class, configuring Task Scheduler and Task Scheduler
Create a Quartzconfig.xml file under the project's Web-inf
<?xml version= "1.0" encoding= "UTF-8"?>
<! DOCTYPE beans Public "-//spring//dtd bean//en" "Http://www.springframework.org/dtd/spring-beans.dtd" >
<beans>
<bean>
<!--register timed task entity--
<bean id= "Lzstonequartztask" class= "Org.lzstone.action.LzstoneQuartzTask"/>
<!--register Timer information--
<bean id= "TaskInfo" class= "Org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean" >
<!--specifying the scheduled task class to perform this is lzstonequartztask-->.
<property name= "TargetObject" >
<ref local= "Lzstonequartztask"/>
</property>
<!--Specify the name of the method to be executed by the Timer task class here's execute-->.
<property name= "Targetmethod" >
<value>execute</value>
</property>
</bean>
<!--Scheduler to configure Timer tasks--
<bean id= "Quartztrigger" class= "Org.springframework.scheduling.quartz.CronTriggerBean" >
<!--declaring entities to run--
<property name= "Jobdetail" >
<ref local= "TaskInfo"/>
</property>
<!--set Run time-
<property name= "Cronexpression" >
<value>0 0 * *?</value>
</property>
</bean>
<!--Register Listener--
<bean id= "Registerquartz" class= "Org.springframework.scheduling.quartz.SchedulerFactoryBean" >
<!--Register Timer entity Collection--
<property name= "Triggers" >
<list>
<ref local= "Quartztrigger"/>
</list>
</property>
</bean>
</beans>
2.3 Startup settings in a Web project
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/QuartzConfig.xml</param-value>
</context-param>

<listener>
<listener-class>
Org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>


There are two popular spring timer configurations: Java's Timer class and Opensymphony's quartz.
1.Java Timer Timer
First, inherit the Java.util.TimerTask class to implement the Run method

Import Java.util.TimerTask;
public class Emailreporttask extends timertask{
@Override
public void Run () {
...
}
}
In spring definition
...
Configuring Spring Timers

<bean id= "Schedulereporttask" class= "Org.springframework.scheduling.timer.ScheduledTimerTask" >
<property name= "TimerTask" ref= "Reporttimertask"/>
<property name= "Period" >
<value>86400000value>
Property>
Bean>
The TimerTask property tells Scheduledtimertask which to run. 86400000 for 24 hours
Start Spring Timer
Spring's Timerfactorybean is responsible for initiating scheduled tasks.

<bean class= "Org.springframework.scheduling.timer.TimerFactoryBean" >
<property name= " Scheduledtimertasks ">
<list><ref bean=" Schedulereporttask "/>list>
property>
Bean >
Scheduledtimertasks displays a list of timer tasks that need to be started.
can delay startup by setting the Delay property
<bean id= "Schedulereporttask" class= " Org.springframework.scheduling.timer.ScheduledTimerTask ">
<property name=" TimerTask "ref=" Reporttimertask "/>
<property name=" period ">
<value>86400000value>
property>
  <property name= "delay" >
<value>3600000value>
property>
bean>
This task we can only specify every 24 hours to run, can not be accurate to start a
2.Quartz timer
First inherit the Quartzjobbean class implementation Executeinternal method

Import Org.quartz.JobExecutionContext;
Import org.quartz.JobExecutionException;
Import Org.springframework.scheduling.quartz.QuartzJobBean;

public class Emailreportjob extends quartzjobbean{
protected void executeinternal (Jobexecutioncontext arg0 )
throws Jobexecutionexception {
...
}
}
defined in spring

<bean id= "Reportjob" class= "Org.springframework.scheduling.quartz.JobDetailBean" >
<property name= " Jobclass ">
<value>EmailReportJobvalue>
property>
<property name=" Jobdataasmap ">
<map>
<entry key= "Courseservice" >
<ref bean= "Courseservice"/>
entry>
Map> ;
property>
Bean>
Here we do not directly declare a emailreportjob bean, but declare a jobdetailbean. This is the characteristic of quartz. Jobdetailbean is a subclass of Quartz's org.quartz.JobDetail, which requires a job object to be set through the Jobclass property. Another special point in the
Jobdetail using quartz is that the Courseservice property of Emailreportjob is indirectly set. The Jobdataasmap property of Jobdetail accepts a map, including various properties set to Jobclass, when. When Jobdetailbean is instantiated, it injects the courseservice bean into the Courseservice attribute of the emailreportjob. The
Start Timer
Quartz Org.quartz.Trigger class describes when and how often to run a quartz job. Spring provides two triggers Simpletriggerbean and Crontriggerbean. The
Simpletriggerbean is similar to Scheduledtimertasks. Specifies the frequency of execution of the work, mimicking the scheduledtimertasks configuration.

<bean id= "Simplereporttrigger" class= "Org.springframework.scheduling.quartz.SimpleTriggerBean" >
< Property Name= "Jobdetail" ref= "Reprotjob"/>
<property name= "Startdelay" >
<value>360000value >
property>
<property name= "Repeatinterval" >
<value>86400000value>
Property >
bean>
Startdelay is also a delayed 1-hour start
Crontriggerbean The exact run time of the specified work

<bean id= "Cronreporttrigger" class= "Org.springframework.scheduling.quartz.CronTriggerBean" >
<property name= "Jobdetail" ref= "Reprotjob"/>
<property name= "Cronexpression" >
<value>0 0 6 * *?value>
Property>
Bean>
The Cronexpression property tells when to trigger. The most mysterious is the cron expression:
The Linux system's scheduled tasks usually have cron to bear. A cron expression has at least 6 (or possibly 7) time elements that have a space separation. From left to right:
1. Seconds 2.3. Hours 4. Date in the month (1-31) 5. Month (1-12 or JAN-DEC) 6. Day of the week (1-7 or Sun-sat) 7. Year (1970-2099)
Each element shows a specified value (such as 6), a range (9-12), a list (9,11,13), or a wildcard character (*). Because 4 and 6 of these two elements are mutually exclusive, they should be set by a question mark (?). To indicate the field that you do not want to set, "/" if the combination of values represents the number of repetitions (10/6 means repeat 6 times every 10 seconds).
Start timer

<bean class= "Org.springframework.scheduling.quartz.SchedulerFactoryBean" >
<property name= "Triggers" >
<list><ref bean= "Cronreporttrigger"/>list>
Property>
Bean>
The Triggers property accepts a set of triggers.

"0 0 12 * *?" trigger 12 o'clock noon every day.
"0 15 10?" * * "trigger 10:15 every day"
"0 15 10 * *?" Daily 10:15 Trigger
"0 15 10 * *?" * "10:15 per day" trigger
"0 15 10 * *?" 2005 "2005-year daily 10:15 Trigger
"0 * 14 * *?" triggers every 1 minutes from 2 o'clock in the afternoon to 2:59 daily
"0 0/5 14 * *?" triggers every 5 minutes from 2 o'clock in the afternoon to 2:55 daily
"0 0/5 14,18 * *?" triggers every 5 minutes from 2 o'clock in the afternoon to 2:55 daily and from 6 o'clock in the afternoon to 6:55
"0 0-5 14 * *?" triggers every 1 minutes from 2 o'clock in the afternoon to 2:05 daily
"0 10,44 14?" 3 WED "2:10 and 2:44 triggers in Wednesday of every March
"0 15 10?" * Mon-fri "Monday to Friday 10:15 trigger
"0 15 10 15 *?" 15th 10:15 per month
"0 L *?" 10:15 on the last day of the month
"0 15 10?" * 6L "Last month of Friday 10:15 Trigger
"0 15 10?" * 6L 2002-2005 "2002 to 2005 the last of the monthly Friday 10:15 trigger
"0 15 10?" * 6#3 "Monthly third Friday 10:15 trigger

Job description in Java and the configuration of job in spring

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.