Build your first Web project: quartz+spring Implement timed tasks

Source: Internet
Author: User
Tags log log

Test process:

First write a simple task class, test the configuration of the Quartz whether the function (the ultimate goal is to achieve the scheduled deletion of temporary storage folder).

The configuration files added in spring are as follows:

<!--timed Task quartz (Spring internal integration) -    <!--task class for periodically emptying temporary folders -    <BeanID= "Taskjob"class= "Cn.itcast.oa.util.TaskJob"></Bean>        <!--define methods in the target bean and bean -    <BeanID= "Job"class= "Org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">        < Propertyname= "TargetObject">            <refLocal= "Taskjob" />        </ Property>        < Propertyname= "Targetmethod">            <!--the name of the method to execute -            <value>Count</value>        </ Property>    </Bean>    <!--define the time of the trigger -    <BeanID= "Cron"class= "Org.springframework.scheduling.quartz.CronTriggerBean">        < Propertyname= "Jobdetail">            <refBean= "Job" />        </ Property>        < Propertyname= "Cronexpression">            <value>0-59 * * * *?</value>        </ Property>    </Bean>    <!--Manage triggers -    <BeanAutowire= "No"class= "Org.springframework.scheduling.quartz.SchedulerFactoryBean">        < Propertyname= "Triggers">            <List>                <refLocal= "Cron" />            </List>        </ Property>    </Bean>

The task classes are as follows:

 PackageCn.itcast.oa.util;/*** Scheduled task, Empty Temp folder * *@authorHaojiahong * * @createtime: 2015-7-21 PM 2:23:55 * **/ Public classTaskjob {Static LongCount = 0;  PublicTaskjob () {System.out.println ("Bean initialized."); }     Public voidDofirst () {Count (); }     Public voidcount () {count++; System.out.print ("Count=");    System.out.println (Count); }}

The final test succeeds with the result of the output as follows: (after the task class is instantiated, the Count method is called every second)

Info: Initializing Spring root Webapplicationcontext16:38:10,184 DEBUG myapplicationcontextutil:24-ApplicationContext to complete the setup ... 16:38:10,200 DEBUG ftpstore:31-the FTP server configuration parameter bean initialized is initialized. Count=1Count=2Count=32015-7-22 16:38:12Org.apache.coyote.http11.Http11Protocol Start Info: Starting Coyote HTTP/1.1 on Http-88882015-7-22 16:38:12org.apache.jk.common.ChannelSocket init info: jk:ajp13 listening on/0.0.0.0:80092015-7-22 16:38:12Org.apache.jk.server.JkMain Start info: JK Running ID=0 TIME=0/16 config=NULL2015-7-22 16:38:12Org.apache.catalina.startup.Catalina Start Information: Server startup in7605Mscount=4Count=5Count=6Count=7Count=8Count=9Count=10Count=11Count=12Count=13Count=14

The following exception occurred during the first configuration:

Caused By:java.lang.IncompatibleClassChangeError:classOrg.springframework.scheduling.quartz.CronTriggerBean hasInterfaceOrg.quartz.CronTrigger asSuper classAt Java.lang.ClassLoader.defineClass1 (Native Method) at Java.lang.ClassLoader.defineClass (classloader.java:621) at Java.security.SecureClassLoader.defineClass (Secureclassloader.java:124) at Org.apache.catalina.loader.WebappClassLoader.findClassInternal (Webappclassloader.java:1817) at Org.apache.catalina.loader.WebappClassLoader.findClass (Webappclassloader.java:872) at Org.apache.catalina.loader.WebappClassLoader.loadClass (Webappclassloader.java:1325) at Org.apache.catalina.loader.WebappClassLoader.loadClass (Webappclassloader.java:1204) at Org.springframework.util.ClassUtils.forName (Classutils.java:211) at Org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass ( Abstractbeandefinition.java:385) at Org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass (Abstractbeanfactory.java :1138)    ... More

The reason is that the quartz version built into the Spring 3.0 version is <2.0 and the interface is incompatible after using the latest quartz package (>2.0).

There are two ways to solve this problem:

1. Reduce the quartz version to 1. X go.

2. Upgrade the spring version to 3.1 +, according to Spring's suggestion, replace the original **triggerbean with **triggerfactorybean, for example Crontriggerbean can be replaced Crontriggerfactorybean. The problem is resolved after the substitution.

Finally, I wrote the task class to delete the Temp folder and its files:

 PackageCn.itcast.oa.util;ImportJava.io.File;ImportOrg.apache.commons.logging.Log;Importorg.apache.commons.logging.LogFactory;/*** Scheduled task, Empty Temp folder * *@authorHaojiahong * * @createtime: 2015-7-21 PM 2:23:55 * **/ Public classTaskjob {PrivateLog log = Logfactory.getlog ( This. GetClass ());  PublicTaskjob () {Log.debug ("Initialize timed task class completion: "); }     Public voidExcetedeljob () {String TempPath= (String) This. Getappconfig (). Getappextprop (). Get ("Filetemppath");        System.out.println (TempPath); if(!delfile (TempPath)) {            return; }    }    Private Booleandelfile (String temppath) {File file=NewFile (TempPath); if(!file.exists ()) {Log.debug ("Folder does not exist"); return false; }        if(File.isfile ()) {file.delete (); Log.debug ("Single File deletion succeeded"); return true; } file[] Files=File.listfiles ();  for(File f:files) {if(F.isfile ()) {f.delete (); Log.debug ("Single file deletion in folder succeeded"); } Else {                 This. Delfile (F.getabsolutepath ()); Log.debug ("Start deleting folders in a folder");        }} file.delete (); return true; }     PublicAppConfig Getappconfig () {return(AppConfig) Applicationutil.getbean ("AppConfig"); }}

Build your first Web project: quartz+spring Implement timed tasks

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.