Spring Quartz Dynamic configuration of timed tasks

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>  
Set in the configuration above:
①targetmethod: Specifies that the test () method in scheduleinfoaction needs to be executed periodically
②concurrent: For the same jobdetail, when more than one trigger is specified, it is likely that the second job will begin before the first job is completed. Specifying concurrent is set to false, multiple jobs do not run concurrently, and the second job will not start until the first job is completed.
③CRONEXPRESSION:0/10 * * * * For every 10 seconds, refer to the schedule.
④triggers: You can place multiple triggers 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 in spring dynamic set Crontrigger method one
(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"/>           <!--Emsservice in  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 the callee's instance 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 {   The         //  runtime can be trigger by dynamically injected scheduler, noting that there are problems with this injection method in some projects. If you encounter an injection problem, you can take the bean to avoid the error 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 the DB ( dbcronexpression) is equal to the task time (originconexpression) in the current quartz thread             //  if equal, the user does not reset the task time in the database, which does not need to be re-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 ("------------------ -------------------------------------------");                }           }               //executes 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 in spring dynamic set Crontrigger method two
In 2 we have been able to implement dynamic configuration cronexception, 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 (like JBoss) will give an error.
In fact, we want the container to go to the database for dbcronexception when it starts, without having to initialize a cronexception. Looking at 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, multiple jobs do 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 (which is placed in the setter method, is because you need to Getcronexpressionfromdb () after you set Scheduleinfomanager, or you can ①② logic in the constructor of your class.
Note that Initializingcrontrigger must 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.