Spring Quartz Dynamic Configuration timed task

Source: Internet
Author: User
1. Simple configuration of quartz in spring
Spring configuration file Quartz.xml:
Java code   <?xml version= "1.0"  encoding= "UTF-8"?>            <! doctype beans public  "-//spring//dtd bean//en"   "http://www.springframework.org/dtd/ Spring-beans.dtd ">   <beans>          <bean id = "Scheduleinfoservice"  class= "Com.erry.tntops.web.task.ScheduleInfoService" >             <property name= "Scheduler"  ref= "SchedulerFactory"/>         </bean>            <bean id= "Jobdetail"  class= " Org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean ">             <property name= "TargetObject"  ref= "ScheduleInfoService"/>           &Nbsp; <property name= "Targetmethod"  value= "test"/>             <property name= "Concurrent"  value= "false"/>         </bean>           <bean id= " Crontrigger " class=" Org.springframework.scheduling.quartz.CronTriggerBean " >              <property name= "JobDetail"  ref= "JobDetail" >             <property name= " Cronexpression ">                  <value>0/10 * * * * ?</value>              </property>         </bean >    &nbsp      <bean id= "Schedulerfactory"  class= " Org.springframework.scheduling.quartz.SchedulerFactoryBean ">             <property name= "triggers" >                 <list>                     <ref local= "CronTrigger"/>                </list>             </property>       </bean >   </beans>  
In the configuration above, set:
①targetmethod: Specifies that the test () method in scheduleinfoaction must be executed periodically
②concurrent: For the same jobdetail, when multiple trigger are specified, it is likely that the second job will begin before the first job completes. Specifies that concurrent is set to false, multiple jobs will not run concurrently, and the second job will not start before the first job completes.
③CRONEXPRESSION:0/10 * * * * * * means to perform every 10 seconds, refer to the schedule.
④triggers: Multiple triggers can be placed in the list by adding additional ref elements.
The Simplejobtest () method in Scheduleinfoaction
Note: This method has no parameters, and if Scheduleinfoaction has two methods test () and test (String argument), spring will only execute the parameterless test ().
Java Code public void Test () {Log.warn ("Uh-oh, JOB is scheduled!" + "' Success ... '); }
2. Quartz dynamically set Crontrigger method in spring
(1), Spring configuration file Quartz.xml:
Java code   <?xml version= "1.0"  encoding= "UTF-8"?>            <! doctype beans public  "-//spring//dtd bean//en"   "http://www.springframework.org/dtd/ Spring-beans.dtd ">   <beans>       <bean id=" Scheduleinfoaction " class=" com.erry.tntops.web.task.ScheduleInfoAction ">            <property name= "Scheduler"  ref= "Schedulerfactory"/>   The Emsservice in the         <!-- ref is the id -->  of the bean configured in XML           <property name= "Emsservice"  ref= "EmsService "/>        </bean>            <bean id= "Jobdetail"  class= "Org.springframework.scheduling.quartz.MethodInvokingJobDetailfactorybean ">            <property name = "TargetObject"  ref= "scheduleinfoaction"/>             <property name= "Targetmethod"  value= "Reschedulejob"/>             <property name= "Concurrent"  value= "false"/>        </bean>           <bean  id= "Crontrigger"  class= "Com.erry.tntops.web.task.InitCronTrigger" >              <property name= "Jobdetail"  ref= "JobDetail"/>              <property name= "CronExpression" >                  <value>0 /10 * * * * ?</value>              </property>         </bean>            <bean id= "Schedulerfactory"  class= " Org.springframework.scheduling.quartz.SchedulerFactoryBean ">             <property name= "triggers" >                 <list>                     <ref local= "CronTrigger"/>                </list>             </property>       </bean >   </beans>  
(2), Class Scheduleinfoaction:
Java code   import org.apache.log4j.logger;   import org.quartz.scheduler;   import org.quartz.schedulerexception;   import  org.springframework.scheduling.quartz.crontriggerbean;      import  java.text.parseexception;   import java.util.date;      Public class  ScheduleInfoAction{       logger logger = logger.getlogger ( Scheduleinfoaction.class);           private Scheduler  scheduler;        //  Set Value injection, passing the setter method to an instance of the callee scheduler        public void setscheduler (Scheduler scheduler)  {            this.scheduler = scheduler;        }          private EmsService emsService;          public void  Setemsservice (emsservice emsservice) {            this.emsservice = emsservice;       }           public void reschedulejob ()  throws SchedulerException {           //  runtime can get trigger through dynamic injection Scheduler, note that this injection method can be problematic in some projects, If you encounter an injection problem, you can take a bean to avoid errors when you run the method.            CronTriggerBean trigger =  ( Crontriggerbean)  scheduler.gettrigger ("Crontrigger",  scheduler.default_group);            logger.info ("*********** trigger: "  + trigger);            string dbcronexpression = getcronexPressionfromdb ();           logger.info ("***********  dbcronexpression:  " + dbcronexpression);            string originconexpression = trigger.getcronexpression ();            logger.info ("*********** originconexpression: "  +  Originconexpression);           //  determine the task time obtained from DB ( dbcronexpression) is equal to the task time (originconexpression) in the current quartz thread             //  if equal, it means that the user did not reset the task time in the database, this situation does not need to reschedulejob            if (!originconexpression.equalsignorecase (dbcronexpression)) {                try{               &nBsp;    trigger.setcronexpression (dbcronexpression);                    scheduler.reschedulejob ("CronTrigger",  scheduler.default_group, trigger);                } catch  (parseexception e)  {                    logger.error ("-------------------  ParseException Error! -------------------");                    e.printstacktrace ();                    logger.error ("------------------ -------------------------------------------");                }           }               //Execute task           logger.info ("task  start time:  " + new date ());            system.out.println ("task test success!");            logger.info ("  task end time:   " + new date ());       }           private string getcronexpressionfromdb () {            String sql =  "Select cron from t_test_task_trigger where  available = 1 and trigger_name =  ' Crontrigger ' ";            return emsservice.Getcron (SQL);       }  }  
3. Quartz dynamically set Crontrigger method in spring two
We have been able to implement dynamic configuration cronexception in 2, but we still need to set a default cronexception:
Java code <property name= "Cronexpression" > &LT;VALUE&GT;0/10 * * *?</value> < /property>
If we take it off, the container (such as JBoss) will give an error.
We actually want the container to go to the database to get dbcronexception when it starts, without having to initialize a cronexception. To observe Crontriggerbean, we need to initialize cronexception, we can create class Initcrontrigger inherit Crontriggerbean, get data initialization cronexception from DB, so the problem is solved.
(1), Spring configuration file Quartz.xml:
Java code   <?xml version= "1.0"  encoding= "UTF-8"?>            <! doctype beans public  "-//spring//dtd bean//en"   "http://www.springframework.org/dtd/ Spring-beans.dtd ">   <beans>          <bean id = "Scheduleinfoaction"  class= "wym.task.ScheduleInfoAction" >            <property name= "Scheduler"  ref= "Schedulerfactory"/>            <property name= "Emsservice"  ref= "EmsService"/>        </bean>           <bean  id= "Jobdetail"  class= "Org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean" >             <property name= "targetObject " ref=" scheduleinfoaction "/>             <property name= "Targetmethod"  value= "Reschedulejob"/>             <!-- concurrent set to False, more than one job will not run concurrently  -->             <property name= "Concurrent"  value= "false"/>         </bean>           < Bean id= "Crontrigger"  class= "Wym.task.InitCronTrigger" >              <property name= "Jobdetail"  ref= "Jobdetail"/>             <!--<property name= "Cronexpression" >-->                 <!--<value>0/30  * * * * ?</value>-->            <!-- </property>-->             <property  name= "Emsservice"  ref= "Emsservice"/>         </bean >           <bean id= "schedulerfactory"  class= " Org.springframework.scheduling.quartz.SchedulerFactoryBean ">             <property name= "triggers" >                 <list>                     <ref local= "CronTrigger"/>                </list>             </property>       </bean>   </ beans>  
(2), Class Initcrontrigger
Note: When injecting the Scheduleinfomanager attribute, we can read the DB task time (in the Setter method, Because you need to getcronexpressionfromdb () after setting the Scheduleinfomanager, you can also ①② the logic into the constructor of the class.
Note that Initializingcrontrigger must be extends Crontriggerbean.
Java code   import com.erry.tntops.ems.service.emsservice;   import  org.springframework.scheduling.quartz.crontriggerbean;      import java.io.serializable ;   import java.text.parseexception;      public class  initcrontrigger extends crontriggerbean implements serializable {        private EmsService emsService;           Public void setemsservice (Emsservice emsservice)  throws ParseException {            this.emsService = emsService;           string cronexception = getcronexceptiondb ();            setcronexpression (cronexception);       }         private string getcronexceptiondb () {            string

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.