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: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");
}
}