Integration of spring and quartz to implement timed task scheduling

Source: Internet
Author: User

There are 2 ways to integrate quartz with spring:

1. Jobdetailbean.

2. Methodinvokejobdetailfactorybean.

The following is a description of the knowledge that is used and understood and mastered.

It is important to note that when using spring integrated quartz, be sure not to forget to introduce spring-support this package:

1. Using Methodinvokejobdetailfactorybean

Applicationtask.xml Configuration

<?xml version="1.0"encoding="UTF-8"? ><beans xmlns="Http://www.springframework.org/schema/beans"Xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:tx="Http://www.springframework.org/schema/tx"XMLNS:AOP="HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"xmlns:context="Http://www.springframework.org/schema/context"xsi:schemalocation="Http://www.springframework.org/schema/beanshttp//www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp//Www.springframework.org/schema/txhttp//www.springframework.org/schema/tx/spring-tx-2.5.xsdhttp//WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOPhttp//www.springframework.org/schema/aop/spring-aop-2.5.xsdhttp//Www.springframework.org/schema/contexthttp//www.springframework.org/schema/context/spring-context-2.5.xsd "><!--Scheduled Tasks downstream callback task--<!--========================1, define the task classes that need to be performed. ========================--<bean id="Notifyquartz" class="com.hsmpay.mobile.timerTask.NotifyTimerAction"> </bean> <!--========================2, and inject the scheduled tasks that need to be performed into the job. ========================--<bean id="Notifyquartzdetail" class="Org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <!--introducing the class to perform tasks--<property name="TargetObject"><refbean="Notifyquartz"/></property> <!--define a method to perform a specific class-<property name="Targetmethod"><value>remoteNotify</value></property> </bean> <!--========================3, dispatch trigger ========================--<bean id="Notifytrigger" class="Org.springframework.scheduling.quartz.CronTriggerBean"> <property name="Jobdetail"><refbean="Notifyquartzdetail"/></property> <property name="cronexpression"> <!--run every five minutes-<!--<value>0  , Ten* *?</value>--> <value>0 0/5* * *?</value><!--<value> second day of the month anniversary </value>0  -  -? * mon-fri--> </property> </bean> <!--====================================================== ==========================================--> <!--half a minute to perform scheduled tasks--<!--========================1, define the task classes that need to be performed. ========================--<bean id="Messagetask" class="Com.hsmpay.mobile.timerTask.MessageTask"></bean> <!--========================2, and inject the scheduled tasks that need to be performed into the job. ========================--<bean id="Onemessagerollbacktaskjobdetail" class="Org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="TargetObject"><refbean="Messagetask"/></property> <property name="Targetmethod"><value>oneTaskJob</value></property> </bean> <!--========================3, dispatch trigger ========================--<bean id="Onemessagestreamrollbacktrigger" class="Org.springframework.scheduling.quartz.CronTriggerBean"> <property name="Jobdetail"> <refbean="Onemessagerollbacktaskjobdetail"/> </property> <property name="cronexpression"> <value>*/ -* * * * *?</value> </property> </bean> <!--========================4, Dispatch factory ========================--<beanclass="Org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <refbean="Notifytrigger"/> </list> </property> </bean> <bean id="Threadpooltaskexecutor" class="Org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> <!--thread Pool maintains a minimum number of threads--<property name="corepoolsize"Value="Ten"/> <!--thread pool to maintain idle time allowed by thread--<property name="Keepaliveseconds"Value=" $"/> <!--thread pool maintains the maximum number of threads--<property name="maxpoolsize"Value=" -"/> < buffer queue used by!--thread pool--<property name="queuecapacity"Value=" -"/> <property name="Rejectedexecutionhandler"> <!--abortpolicy: Throw java.util.concurrent.RejectedExecutionException Exception directly--<!--Caller Runspolicy: The main thread executes the task directly, and then tries to add the next task to the thread pool after execution, which effectively reduces the speed of adding tasks to the thread pool-<!--discardoldestpolicy: Discard old tasks, temporarily unsupported; cause The discarded task cannot be executed again-<!--Discardpolicy: Discards the current task, temporarily does not support it, causes the discarded task to not be executed again--<beanclass="Java.util.concurrent.threadpoolexecutor$callerrunspolicy"/> </property> </bean></beans>

Related code configuration

@Controller ("Notifytimeraction") public class Notifytimeraction {private Logger log = Loggerfactory.getlogger (this.get    Class ()); @Resource (name= "Transorderservice") Transorderservice transorderservice;//Query Order service//set core pool size int corepoolsize    = 5;    Sets the maximum number of threads the thread pool can accept int maximumpoolsize=20;    When the current number of threads is greater than corepoolsize, less than maximumpoolsize, the lifetime of the number of threads exceeding corepoolsize long keepactivetime = 200;    Set the time unit, seconds timeunit timeunit = timeunit.seconds;    Public String url = "Http://localhost:8080/mobile/forwardPort/port.action"; /** * Downstream callback notification, continue to send */public void remotenotify () throws exception{Log.debug ("Test timed task started!!!!!!!!        "); SYSTEM.OUT.PRINTLN ("Test timed task started!!!!!!!!        ");        Transorder order=new Transorder (); Order.setstatus (1);//Set Success Status Order.setclienttype (7);//Set Customer Type 7 interface type Order.setordertypeid (1L);//Payment type/ /Set the queuing policy for the thread pool cache queue to FIFO, and specify a cache queue size of 5 blockingqueue<runnable> workQueue = new ARRAYBLOCKINGQUEUE&LT;RUNNABLE&Gt; (5); Creates a Threadpoolexecutor thread pool object and initializes various parameters of the object Threadpoolexecutor executor = new Threadpoolexecutor (corepoolsize, maximum        Poolsize, Keepactivetime, Timeunit,workqueue);            try {list<transorder> orderlist = transorderservice.searchentitylist (order);            Map<string,object> map=new hashmap<string,object> ();                Prepare to send data downstream for (Transorder transorder:orderlist) {thread thread=new thread (new Runnable () { public void Run () {map.put ("status", Transorder.getstatus ());//Trade Status Map.put ("Ordernum                ", Transorder.getordernum ());//order number Jsonobject Jsonobject = jsonobject.fromobject (map);                Httpclientutil.submitpost (Transorder.getotherdata (), map.tostring (), "UTF-8", 60000, 60000);              }            });            Executor.execute (thread); } executor.shutdown ();//close thread pool} catch (Exception e) {E.printstaCktrace ();        Throw e; }    }}

=============================================================================================================== ===================================================

Second, Jobdetailbean

1. Create a job method that must inherit Quartzjobbean or implement the job method.

 Public class Testjob extends Quartzjobbean {        @Override    protectedvoid  executeinternal ( Jobexecutioncontext arg0) throws jobexecutionexception {        System.  out . println (Timeutils.getcurrenttime ());}    }

2. XML configuration

<?xml version="1.0"encoding="UTF-8"? ><beans xmlns="Http://www.springframework.org/schema/beans"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.xsd "> <bean id="Jobdetail" class="Org.springframework.scheduling.quartz.JobDetailFactoryBean"> <property name="Jobclass"Value="Com.mc.bsframe.job.TestJob"></property> <property name="Durability"Value="true"></property> </bean> <bean id="Simpletrigger" class="Org.springframework.scheduling.quartz.SimpleTriggerFactoryBean"> <property name="Jobdetail" ref="Jobdetail"/> <property name="Startdelay"Value=" the"/> <property name="Repeatinterval"Value=" -"/> </bean> <!--general Management class if the lazy-init='false'Then the container starts executing the scheduler--<bean id="Startquertz"lazy-init="false"Autowire="No" class="Org.springframework.scheduling.quartz.SchedulerFactoryBean"> <!--Management trigger--<property name="triggers"> <list> <refbean="Simpletrigger"/> </list> </property> </bean></beans>

Comprehensive: The basic configuration of the scheduled task is completed.

Description of the three or two methods

With Quartzjobbean, inheritance is required. Using Methodinvokejobdetailfactorybean, you need to specify TargetObject (task instance) and Targetmethod (the method to be executed in the instance)

The latter advantage is no intrusion, business logic is simple, at a glance, the disadvantage is unable to persist (it is not clear this!)

from the experience I use, one of the most important reasons is that when the service is injected into a timed task, the latter can be injected directly, and the former needs to be schedular replaced.

  

Integration of spring and quartz to implement timed task scheduling

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.