Spring Scheduler that supports annotations _spring

Source: Internet
Author: User
Tags dateformat thread class

Https://www.cnblogs.com/jingmoxukong/p/5825806.html

Overview

If you want to use the Task Scheduler feature in spring, you can use spring's own scheduling task framework in addition to the integrated scheduling framework quartz this way.

The advantage of using spring's scheduling framework is that it supports annotations (@Scheduler) and eliminates a large number of configurations.

Real-time trigger scheduling task TaskScheduler Interface

SPRING3 introduces the TaskScheduler interface, which defines an abstract method for scheduling tasks.

Declaration of the TaskScheduler interface:

Public interface TaskScheduler {    scheduledfuture<?> schedule (Runnable task, Trigger Trigger);    Scheduledfuture<?> Schedule (Runnable task, Date starttime);    Scheduledfuture<?> scheduleatfixedrate (Runnable task, Date StartTime, long period);    Scheduledfuture<?> scheduleatfixedrate (Runnable task, long period);    Scheduledfuture<?> Schedulewithfixeddelay (Runnable task, Date StartTime, long delay);    Scheduledfuture<?> Schedulewithfixeddelay (Runnable task, long delay);    }

From the above methods, we can see that TaskScheduler has two important dimensions:

One is the method to dispatch, the run () method of a thread class that implements the Runnable interface, and the other is the trigger condition.

Implementation classes for TaskScheduler interfaces

It has three implementation classes: Defaultmanagedtaskscheduler, Threadpooltaskscheduler

, Timermanagertaskscheduler.

Defaultmanagedtaskscheduler: a Jndi based scheduler.

Timermanagertaskscheduler: Scheduler for Managed Commonj.timers.TimerManager instances.

Threadpooltaskscheduler: Provides a scheduler for thread pool management and implements the Taskexecutor interface so that a single instance can be executed asynchronously as quickly as possible.

Trigger interface

The trigger interface abstracts the method that triggers the condition.

Declaration of the Trigger interface:

Publicinterface Trigger {    Date nextexecutiontime (Triggercontext triggercontext);}

Implementation classes for Trigger interfaces

Crontrigger: The trigger class that implements the Cron rule (same as the quartz cron rule).

Periodictrigger: A trigger class that implements a periodic rule (for example, defining trigger start time, interval time, and so on).

Complete example

The function of implementing a dispatch task has the following key points:

(1) Define Scheduler

Configuring in Spring-bean.xml

Using the Task:scheduler tag to define a thread pool scheduler size 10, spring instantiates a threadpooltaskscheduler.

Note: Do not forget to introduce xsd:

Http://www.springframework.org/schema/task

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

<?xml version= "1.0" encoding= "       UTF-8" ><beans "xmlns=" Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"       xmlns:mvc= "Http://www.springframework.org/schema/mvc "       xmlns:task=" Http://www.springframework.org/schema/task "       xsi:schemalocation=" http:// Www.springframework.org/schema/beans       Http://www.springframework.org/schema/beans/spring-beans-3.1.xsdhttp ://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.1.xsdhttp:// Www.springframework.org/schema/task       http://www.springframework.org/schema/task/spring-task-3.1.xsd ">  <mvc:annotation-driven/>  <task:scheduler id= "Myscheduler" pool-size= "ten"/></beans>

(2) Define scheduling tasks

Defines the thread class that implements the Runnable interface.

Import Org.slf4j.logger;import Org.slf4j.loggerfactory;public class Demotask implements Runnable {    final Logger Logger = Loggerfactory.getlogger (This.getclass ());    @Override public    Void Run () {        logger.info (' Call Demotask.run ');    }

(3) Assemble Scheduler and perform dispatch task

Assemble TaskScheduler in a controller class using @autowired annotations.

Then mobilize the TaskScheduler object's schedule method to start the scheduler, you can perform the scheduling task.

Import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.scheduling.taskscheduler;import Org.springframework.scheduling.support.crontrigger;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.RequestMethod @Controller @requestmapping ("/scheduler") public class Schedulercontroller {        @Autowired    TaskScheduler Scheduler;        @RequestMapping (value = "/start", method = requestmethod.post) public    void Start () {        scheduler.schedule (new Demotask (), New Crontrigger ("0/5 * * * *"));    }

Access the/scheduler/start interface, start the scheduler, you can see the following log content:

13:53:15.010 [myScheduler-1] [INFO] O.zp.notes.spring.scheduler.demotask.run-call Demotask.run

13:53:20.003 [myScheduler-1] [INFO] O.zp.notes.spring.scheduler.demotask.run-call Demotask.run

13:53:25.004 [MyScheduler-2] [INFO] O.zp.notes.spring.scheduler.demotask.run-call Demotask.run

13:53:30.005 [myScheduler-1] [INFO] O.zp.notes.spring.scheduler.demotask.run-call Demotask.run

How to use @Scheduler

A big highlight of spring's scheduler is the @scheduler annotation, which eliminates a lot of cumbersome configuration. Start annotations

Use the @scheduler annotation to first use the <task:annotation-driven>

Start the annotation switch.

Cases:

<?xml version= "1.0" encoding= "       UTF-8" ><beans "xmlns=" Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"       xmlns:mvc= "Http://www.springframework.org/schema/mvc "       xmlns:task=" Http://www.springframework.org/schema/task "       xsi:schemalocation=" http:// www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.1.xsdhttp:// www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.1.xsdhttp:// Www.springframework.org/schema/taskhttp://www.springframework.org/schema/task/spring-task-3.1.xsd ">  <mvc:annotation-driven/>  <task:annotation-driven executor= "Myexecutor" scheduler= "Myscheduler"/>  <task:executor id= "Myexecutor" pool-size= "5"/> <task:scheduler id=  "Myscheduler" pool-size= "10"/ ></beans>

@Scheduler define trigger conditions

Example: Use Fixeddelay to specify that the trigger condition is executed every 5000 milliseconds. Note: You must be able to execute 5,000 seconds after the last scheduled success.

@Scheduled (fixeddelay=5000)

Publicvoid dosomething () {

Something that should execute periodically

}

Example: Use Fixedrate to specify that the trigger condition is executed every 5000 milliseconds. Note: Regardless of whether the previous dispatch was successful, it must be executed after 5,000 seconds.

@Scheduled (fixedrate=5000)
Publicvoid dosomething () {
Something that should execute periodically
}

Example: Using InitialDelay specifies that the method does not start scheduling until 1000 milliseconds is initialized.

@Scheduled (initialdelay=1000, fixedrate=5000)
Publicvoid dosomething () {
Something that should execute periodically
}

Example: Use a cron expression to specify that the trigger condition is executed every 5000 milliseconds. Cron rules are consistent with cron rules in quartz.

@Scheduled (cron= "*/5 * * * * MON-FRI")
Publicvoid dosomething () {
Something that should execute in weekdays only
}

Complete example

(1) Start the annotation switch and define the scheduler and actuator

<?xml version= "1.0" encoding= "       UTF-8" ><beans "xmlns=" Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"       xmlns:mvc= "Http://www.springframework.org/schema/mvc "       xmlns:task=" Http://www.springframework.org/schema/task "       xsi:schemalocation=" http:// Www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.1.xsd       http ://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.1.xsdhttp:// Www.springframework.org/schema/taskhttp://www.springframework.org/schema/task/spring-task-3.1.xsd ">  <mvc:annotation-driven/>  <task:annotation-driven executor= "Myexecutor" scheduler= "Myscheduler"/>  <task:executor id= "Myexecutor" pool-size= "5"/> <task:scheduler id=  "Myscheduler" pool-size= "10"/ ></beans>

(2) Use @scheduler annotation to modify a method to be scheduled

The following example shows the different ways in which the @scheduler annotation defines the trigger condition.

Importorg.slf4j.logger;import Org.slf4j.loggerfactory;import org.springframework.scheduling.annotation.Scheduled ; Import Org.springframework.stereotype.component;import java.text.simpledateformat;import java.util.Date;/** * @ Title Scheduledtasks * @description using the @scheduler annotation Schedule Task Example * @author VICOTR Zhang * @date August 31, 2016 * * * @Componentpublic Clas    S Scheduledmgr {private final SimpleDateFormat DateFormat = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");    Final Loggerlogger = Loggerfactory.getlogger (This.getclass ()); Print initialization time in/** * constructor/public scheduledmgr () {logger.info (' current time: {} ', Dateformat.format (new Date    ())); The/** * Fixeddelay property defines the schedule interval.     The schedule needs to wait for the last scheduled execution to complete.        */@Scheduled (Fixeddelay = 5000) public void Testfixeddelay () throws Exception {Thread.Sleep (6000);    Logger.info ("Current time: {}", Dateformat.format (New Date ()); The/** * Fixedrate property defines the schedule interval.     The schedule does not wait for the last scheduled execution to complete. * * @Scheduled (fixedrate = 5000) publicvoid Testfixedrate () throws Exception {Thread.Sleep (6000);    Logger.info ("Current time: {}", Dateformat.format (New Date ()); The/** * InitialDelay property defines the startup delay time after initialization/@Scheduled (InitialDelay = 1000, fixedrate = 5000) public void test        InitialDelay () throws Exception {Thread.Sleep (6000);    Logger.info ("Current time: {}", Dateformat.format (New Date ());    The/** * Cron attribute supports the use of cron expressions to define trigger conditions/@Scheduled (cron = "0/5 * * * *")        public void Testcron () throws Exception {Thread.Sleep (6000);    Logger.info ("Current time: {}", Dateformat.format (New Date ()); }}

I deliberately set the trigger method interval is 5s, and the method is Thread.Sleep (6000); This ensures that the method cannot be executed before the next scheduled trigger point, and look at the performance of the various ways.

When you start the Spring project, spring scans the @component annotation and then initializes the scheduledmgr.

Spring then scans the @scheduler annotations and initializes the scheduler. The scheduler starts working with the trigger condition matching and outputs the log.

Intercepts part of the print log for analysis.

10:58:46.479 [localhost-startstop-1] [INFO] o.z.n.s.scheduler.scheduledtasks.<init>-current time:2016-08-31 10:58:4610:58:52.523 [myScheduler-1] [INFO] o.z.n.s.scheduler.scheduledtasks.testfixedrate-current time:2016-08-31 10:58:5210:58:52.523 [myScheduler-3] [INFO] o.z.n.s.scheduler.scheduledtasks.testfixeddelay-current time: 2016-08-31 10:58:5210:58:53.524 [myScheduler-2] [INFO] O.z.n.s.scheduler.scheduledtasks.testinitialdelay-current Time:2016-08-31 10:58:5310:58:55.993 [myScheduler-4] [INFO] o.z.n.s.scheduler.scheduledtasks.testcron-current time: 2016-08-31 10:58:5510:58:58.507 [myScheduler-1] [INFO] o.z.n.s.scheduler.scheduledtasks.testfixedrate-current time: 2016-08-31 10:58:5810:58:59.525 [myScheduler-5] [INFO] O.z.n.s.scheduler.scheduledtasks.testinitialdelay-current Time:2016-08-31 10:58:5910:59:03.536 [myScheduler-3] [INFO] O.z.n.s.scheduler.scheduledtasks.testfixeddelay- Current time:2016-08-31 10:59:0310:59:04.527 [myScheduler-1] [INFO] O. z.n.s.scheduler.scheduledtasks.testfixedrate-current time:2016-08-31 10:59:0410:59:05.527 [myScheduler-4] [INFO] O.z.n.s.scheduler.scheduledtasks.testinitialdelay-current time:2016-08-31 10:59:0510:59:06.032 [MyScheduler-2] [ Info] o.z.n.s.scheduler.scheduledtasks.testcron-current time:2016-08-31 10:59:0610:59:10.534 [myScheduler-9] [INFO] O.z.n.s.scheduler.scheduledtasks.testfixedrate-current time:2016-08-31 10:59:1010:59:11.527 [myScheduler-10] [INFO ] O.z.n.s.scheduler.scheduledtasks.testinitialdelay-current time:2016-08-31 10:59:1110:59:14.524 [myScheduler-4] [ INFO] o.z.n.s.scheduler.scheduledtasks.testfixeddelay-current time:2016-08-31 10:59:1410:59:15.987 [myScheduler-6] [INFO] o.z.n.s.scheduler.scheduledtasks.testcron-current time:2016-08-31 10:59:15

The construction method is printed once, and the time point is 10:58:46.

Testfixedrate print four times, each interval 6 seconds. Note that fixedrate does not wait for the last scheduled execution to complete and executes immediately when the interval is reached.

Testfixeddelay print three times, each interval is greater than 6 seconds, and the time is not fixed. Note that Fixeddelay waits until the last scheduled execution succeeds, and then executes the calculation interval.

Testinitialdelay first scheduling time and construction method scheduling time is 7 seconds apart. Description, InitialDelay waits for a specified delay to start scheduling after initialization.

Testcron Print three times, the interval is not 5 seconds or 6 seconds, it is obvious that Cron waits until the last scheduled execution succeeds, and then executes the time interval.

In addition, you can see from the log that there are up to 10 threads in the print log, and that the scheduler thread pool configuration in 2.1 is in effect.

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.