About Spring timed task (timer) usage

Source: Internet
Author: User

    • Several implementations of spring timed tasks
    • Several implementations of spring timed tasks
    • A Classification
    • From the implementation of the technology to classify, there are currently three kinds of technology (or three products):
    • From the inheritance of the job class, you can be divided into two categories:
    • From the trigger time of task scheduling, here is mainly for the job use of the trigger, mainly the following two kinds:
    • Two Usage Notes
    • Quartz
    • First, the job class inherits from a specific base class: Org.springframework.scheduling.quartz.QuartzJobBean.
    • Second, the job class does not inherit from a particular base class.
    • Spring-task
    • First: How to configure Files
    • Second: Use annotations as a form of
Several implementations of spring timed tasksBlog Category:
    • Spring Framework

Quartzspringspring-task Timing Task Annotations

Several implementations of spring timed tasks

Recent project development needs to perform some scheduled tasks, such as the need to analyze the log information of the day before the morning, to take this opportunity to collate some of the timing of the implementation of the task, because the project uses the spring framework, so I will combine

Spring Framework to introduce.

A Classification
    • From the implementation of the technology to classify, there are currently three kinds of technology (or three products):
    1. Java comes with the Java.util.Timer class, which allows you to dispatch a Java.util.TimerTask task. Using this method allows your program to execute at a certain frequency, but not at a specified time. Generally used less, this article will not do a detailed introduction.

    2. Using quartz, this is a powerful scheduler that allows your program to execute at a specified time, and can be executed at a certain frequency, which is slightly more complex to configure, and will be described in more detail later.

    3. SPRING3.0 's own task, which can be seen as a lightweight quartz, is much simpler to use than quartz and will be introduced later.

    • From the inheritance of the job class, you can be divided into two categories:
    1. Job classes need to inherit from a particular job class base class. The need to inherit from the Org.springframework.scheduling.quartz.quartzjobbean;java.util.timer in quartz is required to inherit from Java.util.TimerTask.

    2. The job class is a normal Java class and does not need to inherit from any base class.

Note: A second approach is recommended, because the classes are generic and do not need to be treated differently beforehand.

    • From the trigger time of task scheduling, here is mainly for the job use of the trigger, mainly the following two kinds:
    1. Fires once every specified time, and the corresponding trigger in quartz is: Org.springframework.scheduling.quartz.SimpleTriggerBean

    2. Each time it is specified, it is triggered once, and the corresponding scheduler in Quartz is: Org.springframework.scheduling.quartz.CronTriggerBean

Note: These two triggers are not available for each task, such as the Java.util.TimerTask task, which can only be used for the first type. Both quartz and spring tasks can support both of these triggering conditions.

Two Usage Notes

Details how each task scheduling tool is used, including quartz and spring task two.

Quartz first, the job class inherits from a specific base class: Org.springframework.scheduling.quartz.QuartzJobBean.

First step: Define the Job class

Java code

  1. Import Org.quartz.JobExecutionContext;

  2. Import org.quartz.JobExecutionException;

  3. Import Org.springframework.scheduling.quartz.QuartzJobBean;

  4. public class Job1 extends Quartzjobbean {

  5. private int timeout;

  6. private static int i = 0;

  7. After scheduling the factory instantiation, execute the schedule after timeout time

  8. public void setTimeout (int timeout) {

  9. This.timeout = timeout;

  10. }

  11. /**

  12. * Specific tasks to dispatch

  13. */

  14. @Override

  15. protected void Executeinternal (Jobexecutioncontext context)

  16. Throws Jobexecutionexception {

  17. SYSTEM.OUT.PRINTLN ("Timed Task Execution ...");

  18. }

  19. }

Step Two: Configure the job class in the spring configuration file Jobdetailbean

XML code

    1. <bean name= "Job1" class= "Org.springframework.scheduling.quartz.JobDetailBean" >

    2. <property name= "Jobclass" value= "Com.gy.Job1"/>

    3. <property name= "Jobdataasmap" >

    4. <map>

    5. <entry key= "Timeout" value= "0"/>

    6. </map>

    7. </property>

    8. </bean>

Description: Org.springframework.scheduling.quartz.JobDetailBean has two properties, the Jobclass property is the task class that we define in Java code, and the Jobdataasmap property is the attribute value that needs to be injected into the task class.

Step three: Configure trigger mode for job scheduling (triggers)

There are two types of job triggers for quartz, namely

Org.springframework.scheduling.quartz.SimpleTriggerBean

Org.springframework.scheduling.quartz.CronTriggerBean

The first type of Simpletriggerbean, which only supports calling tasks at a certain frequency, such as running every 30 minutes.

The configuration is as follows:

XML code

    1. <bean id= "Simpletrigger" class= "Org.springframework.scheduling.quartz.SimpleTriggerBean" >

    2. <property name= "Jobdetail" ref= "Job1"/>

    3. <property name= "Startdelay" value= "0"/><!--scheduling factory instantiation, after 0 seconds to execute the schedule--

    4. <property name= "Repeatinterval" value= "a"/><!--dispatched every 2 seconds--

    5. </bean>

The second type of Crontriggerbean, which is supported to run once at a specified time, such as 12:00 per day.

The configuration is as follows:

XML code

    1. <bean id= "Crontrigger" class= "Org.springframework.scheduling.quartz.CronTriggerBean" >

    2. <property name= "Jobdetail" ref= "Job1"/>

    3. <!-run one time every 12:00

    4. <property name= "cronexpression" value= "0 0 * *?"/>

    5. </bean>

See appendix for syntax for cronexpression expressions.

Fourth Step: Configure the Dispatch factory

XML code

    1. <bean class= "Org.springframework.scheduling.quartz.SchedulerFactoryBean" >

    2. <property name= "Triggers" >

    3. <list>

    4. <ref bean= "Crontrigger"/>

    5. </list>

    6. </property>

    7. </bean>

Description: This parameter specifies the name of the trigger that was previously configured.

Fifth step: Launch your app and deploy the project to Tomcat or other containers.

Second, the job class does not inherit from a particular base class.

Spring can support this approach thanks to two classes:

Org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean

Org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean

These two classes correspond to the two ways in which spring supports the task scheduling, that is, the timer task mode and the Quartz method that the Java comes from earlier in this article. Here I only write Methodinvokingjobdetailfactorybean usage, the advantage of using this class is that our task class no longer needs to inherit from any class, but the normal pojo.

First step: Writing task classes

Java code

    1. public class Job2 {

    2. public void DoJob2 () {

    3. System.out.println ("Do not inherit Quartzjobbean mode-schedule in progress ...");

    4. }

    5. }

As you can see, this is an ordinary class, and there is a method.

Step Two: Configure the Job class

XML code

    1. <bean id= "Job2"

    2. class= "Org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean" >

    3. <property name= "TargetObject" >

    4. <bean class= "Com.gy.Job2"/>

    5. </property>

    6. <property name= "Targetmethod" value= "DoJob2"/>

    7. <property name= "Concurrent" value= "false"/><!--job not concurrently dispatched--

    8. </bean>

Note: This step is a critical step, declaring a Methodinvokingjobdetailfactorybean with two key properties: targetobject Specifies the task class, Targetmethod specifies the method to run. The next step is the same as the method one, and for completeness, it is also posted.

Step three: Configure trigger mode for job scheduling (triggers)

There are two types of job triggers for quartz, namely

Org.springframework.scheduling.quartz.SimpleTriggerBean

Org.springframework.scheduling.quartz.CronTriggerBean

The first type of Simpletriggerbean, which only supports calling tasks at a certain frequency, such as running every 30 minutes.

The configuration is as follows:

XML code

    1. <bean id= "Simpletrigger" class= "Org.springframework.scheduling.quartz.SimpleTriggerBean" >

    2. <property name= "Jobdetail" ref= "Job2"/>

    3. <property name= "Startdelay" value= "0"/><!--scheduling factory instantiation, after 0 seconds to execute the schedule--

    4. <property name= "Repeatinterval" value= "a"/><!--dispatched every 2 seconds--

    5. </bean>

The second type of Crontriggerbean, which is supported to run once at a specified time, such as 12:00 per day.

The configuration is as follows:

XML code

    1. <bean id= "Crontrigger" class= "Org.springframework.scheduling.quartz.CronTriggerBean" >

    2. <property name= "Jobdetail" ref= "Job2"/>

    3. <!-run one time every 12:00

    4. <property name= "cronexpression" value= "0 0 * *?"/>

    5. </bean>

The above two kinds of scheduling methods according to the actual situation, choose one can.

Fourth Step: Configure the Dispatch factory

XML code

    1. <bean class= "Org.springframework.scheduling.quartz.SchedulerFactoryBean" >

    2. <property name= "Triggers" >

    3. <list>

    4. <ref bean= "Crontrigger"/>

    5. </list>

    6. </property>

    7. </bean>

Description: This parameter specifies the name of the trigger that was previously configured.

Fifth step: Launch your app and deploy the project to Tomcat or other containers.

To this, spring in Quartz basic configuration is finished, of course, before using, to import the corresponding spring package and quartz package, these will not be said.

In fact, it can be seen that quartz configuration seems quite complex, there is no way, because Quartz is actually a heavyweight tool, if we just want to simply perform a few simple scheduled tasks, there is no simpler tool, there!

See my introduction to Spring task in the following section.

Spring-task

The previous section describes the use of quartz in spring, this article describes Spring3.0 's self-developed scheduled Task tool, spring task, which can be compared to a lightweight quartz, and is simple to use, except that spring-related packages do not require additional packages. and two types of annotations and configuration files are supported

form, the two approaches are described below.

First: How to configure Files

First step: Writing Job classes

That is, the ordinary Pojo, as follows:

Java code

    1. Import Org.springframework.stereotype.Service;

    2. @Service

    3. public class Taskjob {

    4. public void Job1 () {

    5. SYSTEM.OUT.PRINTLN ("Task in progress ... ”);

    6. }

    7. }

Step Two: Add namespaces and descriptions to the spring configuration file header

XML code

    1. <beans xmlns= "Http://www.springframework.org/schema/beans"

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

    3. 。。。。。。

    4. xsi:schemalocation= "Http://www.springframework.org/schema/task http://www.springframework.org/schema/task/ Spring-task-3.0.xsd ">

Step three: Set up specific tasks in the spring configuration file

XML code

    1. <task:scheduled-tasks>

    2. <task:scheduled ref= "Taskjob" method= "job1" cron= "0 * * * * *?" />

    3. </task:scheduled-tasks>

    4. <context:component-scan base-package= "Com.gy.mytask"/>

Description: The ref parameter specifies the task class, method specified is required to run methods, cron and cronexpression expression, the specific wording is not introduced here, the details of the above article appendix.

<context:component-scan base-package= "Com.gy.mytask"/> This configuration is not much said, spring scanning annotations used.

The configuration is complete here, it is not very simple.

Second: Use annotations as a form of

Maybe we don't want to write a task class to be configured in an XML file, we can use the annotation @scheduled, and we'll look at the definition of the annotation in the source file:

Java code

    1. @Target ({Java.lang.annotation.ElementType.METHOD, Java.lang.annotation.ElementType.ANNOTATION_TYPE})

    2. @Retention (Retentionpolicy.runtime)

    3. @Documented

    4. Public @interface Scheduled

    5. {

    6. Public abstract String cron ();

    7. Public abstract long Fixeddelay ();

    8. Public abstract long fixedrate ();

    9. }

It can be seen that the note has three methods or parameters, respectively, that means:

Cron: Specifying cron expressions

Fixeddelay: Official documentation explains: An interval-based trigger where the interval is measured from the completion time of the previous task. The time unit value is measured in milliseconds. That is, the interval from the start of the previous task to the start of the next task, in milliseconds.

Fixedrate: Official documentation explains: An interval-based trigger where the interval are measured from the start time of the previous task. The time unit value is measured in milliseconds. The interval from the start of the previous task to the start of the next task, in milliseconds.

Let me configure it below.

First step: Writing Pojo

Java code

    1. Import org.springframework.scheduling.annotation.Scheduled;

    2. Import org.springframework.stereotype.Component;

    3. @Component ("Taskjob")

    4. public class Taskjob {

    5. @Scheduled (cron = "0 0 3 * *?")

    6. public void Job1 () {

    7. SYSTEM.OUT.PRINTLN ("Task in progress ... ”);

    8. }

    9. }

Step Two: Add the task-related configuration:

XML code

  1. <?xml version= "1.0" encoding= "UTF-8"?>

  2. <beans xmlns= "Http://www.springframework.org/schema/beans"

  3. Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"

  4. xmlns:context= "Http://www.springframework.org/schema/context"

  5. xmlns:tx= "Http://www.springframework.org/schema/tx"

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

  7. Xsi:schemalocation= "

  8. Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

  9. HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

  10. Http://www.springframework.org/schema/context

  11. Http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd

  12. Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd

  13. Http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd "

  14. Default-lazy-init= "false" >

  15. <context:annotation-config/>

  16. Configuration of <!-spring scan annotations--

  17. <context:component-scan base-package= "Com.gy.mytask"/>

  18. <!-Open this configuration, spring will recognize @scheduled annotations--

  19. <task:annotation-driven scheduler= "Qbscheduler" mode= "proxy"/>

  20. <task:scheduler id= "Qbscheduler" pool-size= "ten"/>

Description: Theoretically only need to add <task:annotation-driven/> This sentence configuration can be, these parameters are not necessary.

OK configuration is complete, of course, Spring task has a lot of parameters, I do not explain, specifically refer to the XSD document HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TASK/SPRING-TASK-3.0.XSD.

Appendix:

Cronexpression configuration instructions, specific use and parameters please Baidu Google

Special characters allowed for field allowed values

Seconds 0-59,-*/

Sub 0-59,-*/

Hours 0-23,-*/

Date 1-31,-*? /L W C

Month 1-12 or JAN-DEC,-*/

Week 1-7 or Sun-sat,-*? /L C #

Year (optional) leave blank, 1970-2099,-*/

-Interval

* Wildcard Characters

? You don't want to set that field.

Here are just a few examples.

Cron expression meaning

"0 0 12 * *?" Triggered 12 o'clock noon every day

"0 15 10?" * * "trigger 10:15 every day"

"0 15 10 * *?" Triggered 10:15 daily

"0 15 10 * *?" * "10:15 per day" trigger

"0 15 10 * *?" 2005 "2005-year daily 10:15 Trigger

"0 * 14 * *?" Daily from 2 o'clock in the afternoon to 2:59 per minute trigger

"0 0/5 14 * *?" Every 5 minutes from 2 o'clock in the afternoon to 2:55

"0 0/5 14,18 * *?" Daily from 2 o'clock in the afternoon to 2:55 and from 6 to 6:55 every 5 minutes for two time periods

"0 0-5 14 * *?" Daily 14:00 to 14:05 triggers 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

About Spring timed task (timer) usage

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.