1.在需要加載spring的配置文件裏spring.xml / applicationContext.xml 添加
- xmlns:task="http://www.springframework.org/schema/task"
- xsi:schemaLocation="
- http://www.springframework.org/schema/task
- http://www.springframework.org/schema/task/spring-task-3.0.xsd
2.配置自動調度的包和定時開關
-
<!--
使用註解 -->
-
<context:annotation-config />
- <!-- 自動調度需要掃描的包 -->
- <context:component-scan base-package="*" />
- <task:executor id="executor" pool-size="5" />
- <task:scheduler id="scheduler" pool-size="10" />
- <task:annotation-driven executor="executor" scheduler="scheduler" />
3.配置調度和註解調度
- <!-- 配置調度 需要在類名前添加 @Service -->
- <!--
- <task:scheduled-tasks>
- <task:scheduled ref="demoTask" method="myTestWork" cron="0/10 * * * * ?"/>
- </task:scheduled-tasks>
- -->
- <!-- 不通過配置調度,需要在類名前 @Component/@Service,在方法名 前添加@Scheduled(cron="0/5 * * * * ? ")-->
4.在web.xml配置裏添加啓動時要掃描的配置文件和監聽
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>/WEB-INF/applicationContext*.xml</param-value>
- </context-param>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
5.添加調度的包
6.類測試
- @Service
- public class demo {
- @Scheduled(cron="0/5 * * * * ? ")
- public void myTestWork(){
- System.out.println("ssss");
- }
- }