0. Introduction
Previous article: A few basic methods of spring integrated quartz are mentioned.
In the actual use of time, often in a scheduled task to invoke a business class method, the use of Quartzjobbean and methodinvokejobdetailfactorybean the difference is out.
First, Quartzjobbean
In the job class that inherits Quartzjobbean, a null pointer exception is reported when using Xxservice, because the Job object was created quartz when it was created using this method, and Xxxservice was created by spring. The two are not the same system, so using spring-managed objects in the job class will report null pointer exceptions.
The specific usage scenarios are as follows:
Public class extends Quartzjobbean { @Autowired private testservice Testsevice; @Override protectedvoidthrows jobexecutionexception { Testsevice.sayhi (); System.out.println (Timeutils.getcurrenttime ());} }
The solution is to replace the system default Schedulerfactory
Public class extends adaptablejobfactory { @Autowired private autowirecapablebeanfactory Capablebeanfactory; @Override protectedthrows Exception { Object jobinstance= Super. Createjobinstance (bundle); Capablebeanfactory.autowirebean (jobinstance); return Super . Createjobinstance (bundle); }}
Then configure in the XML:
<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "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= "Quartzfactory" class= " Com.mc.bsframe.job.BsQuartzJobFactory "></bean> <BeanID= "Jobdetail"class= "Org.springframework.scheduling.quartz.JobDetailFactoryBean"> < Propertyname= "Jobclass"value= "Com.mc.bsframe.job.TestJob"></ Property> < Propertyname= "Durability"value= "true"></ Property> </Bean> <BeanID= "Simpletrigger"class= "Org.springframework.scheduling.quartz.SimpleTriggerFactoryBean"> < Propertyname= "Jobdetail"ref= "Jobdetail" /> < Propertyname= "Startdelay"value= " the" /> < Propertyname= "Repeatinterval"value= "$" /> </Bean> <!--General Management Class if you lazy-init= ' false ' then the container starts executing the scheduler - <BeanID= "Startquertz"Lazy-init= "false"Autowire= "No"class= "Org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name= "Jobfactory" ref= "Quartzfactory" ></Property> <!--Management Trigger - < Propertyname= "Triggers"> <List> <refBean= "Simpletrigger" /> </List> </ Property> </Bean></Beans>
Second, the use of Methodinvokejobdetailfactorybean
Because the objects are created when spring is created, they can be used directly. Based on this, we recommend that you use this method for integration, convenient and simple.
Quartz Summary (ii): Use of business classes in timed tasks (Xxservice)