1.使用注解方式注册任务,在spring配置文件中添加如下信息
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
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
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<context:component-scan base-package="com.steven.ssm"></context:component-scan>
<task:annotation-driven/>
</beans>
2.注册一个简单的任务,它每逢0秒执行
@Component
public class MyFirstSpringJob {
@Scheduled(cron = "0 * * * * ?")
public void run() {
System.out.println("MyFirstSpringJob......");
try{
Thread.sleep(5000);
}catch (Exception e){
}
}
}
3.同时执行多个任务,且某些任务耗时较长,要配线程池
<task:annotation-driven scheduler="myScheduler"/>
<task:scheduler id="myScheduler" pool-size="10"/>
@Component
public class MySecondSpringJob {
@Scheduled(cron = "3 * * * * ?")
public void run() {
System.out.println("MySecondSpringJob......");
}
}
4.测试结果