Build the simplest spring Scheduled Tasks project:
1. Register spring with the Web. XML in:
1 <!--loading the spring container -2 <Context-param>3 <Param-name>Contextconfiglocation</Param-name>4 <Param-value>/web-inf/classes/spring/applicationcontext-*.xml</Param-value>5 </Context-param>6 <Listener>7 <Listener-class>Org.springframework.web.context.ContextLoaderListener</Listener-class>8 </Listener>
2. Need to tell spring where to scan the component, where I use annotations, so to tell spring that we are registering the task using annotations, my configuration file is Applicationcontext-service.xml
1 <Beansxmlns= "Http://www.springframework.org/schema/beans"2 Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"3 Xmlns:mvc= "Http://www.springframework.org/schema/mvc"4 Xmlns:context= "Http://www.springframework.org/schema/context"5 XMLNS:AOP= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"6 Xmlns:tx= "Http://www.springframework.org/schema/tx"7 Xmlns:task= "Http://www.springframework.org/schema/task"8 xsi:schemalocation= "Http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 9 Http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsdTen Http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd One Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.2.xsd A http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd - Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context-3.2.xsd "> - <!--Service of the news - the <!--<bean id= "Newsservice" class= "Com.ssm.service.impl.NewsServiceImpl"/> - - <Context:component-scanBase-package= "com.ssm.service.*"></Context:component-scan> - <Context:annotation-config/> - <Task:annotation-driven/>//using annotations to implement spring's scheduled Tasks + - <!--This configuration is enabled for spring to recognize @scheduled annotations - + <!--<task:annotation-driven scheduler= "Qbscheduler" mode= "proxy"/> A <task:scheduler id= "Qbscheduler" pool-size= "ten"/> - at </Beans>
3. Register a simple task, create a new package task under the service, and build a spider class, the contents of the class are executed every 10 seconds, print a statement
1 PackageCom.ssm.service.task;2 3 Importjava.util.Date;4 5 Importorg.springframework.scheduling.annotation.Scheduled;6 Importorg.springframework.stereotype.Component;7 ImportOrg.springframework.stereotype.Service;8 9 Ten@Component ("Spider") One Public classSpider { A -@Scheduled (fixedrate=10*1000) - Public voidgetnews () { theSystem.out.println (NewDate () + "-------Getnews"); - } -}
4. Operation Result:
Implementation of Spring's simple scheduled task