定时执行某段代码的功能,或者隔一段时间执行一次。
Spring框架中是使用@Scheduled注解来实现定时任务的。
首先在配置文件头部的必须要有:
xmlns:task="http://www.springframework.org/schema/task"
其次xsi:schemaLocation必须为其添加:
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.0.xsd
然后spring扫描过程必须涵盖定时任务类所在的目录:
context:component-scan base-package="com.xx.xx" />
即@Scheduled注解的定时任务,能够被扫描到
然后设置动作启用定时任务
<task:annotation-driven/>
最后,定义定时任务类
如下面代码所示:
@Scheduled(cron="0 0/1 * * * ?")
public void executeTask() {
// TODO Auto-generated method stub
System.out.println("*************************");
System.out.println("**当前的时间为:"+new Timestamp((new Date()).getTime()));
System.out.println("*************************");
}
需要注意的几点:
1、spring的@Scheduled注解 需要写在实现上、
2、 定时器的任务方法不能有返回值(如果有返回值,spring初始化的时候会告诉你有个错误、需要设定一个proxytargetclass的某个值为true)
3、实现类上要有组件的注解@Component
另外,@Scheduled中的cron参数定义了执行的频率。
一个cron表达式有至少6个(也可能7个)有空格分隔的时间元素。
按顺序依次为
秒(0~59)
分钟(0~59)
小时(0~23)
天(月)(0~31,但是你需要考虑你月的天数)
月(0~11)
天(星期)(1~7 1=SUN 或 SUN,MON,TUE,WED,THU,FRI,SAT)
7.年份(1970-2099)
其中每个元素可以是一个值(如6),一个连续区间(9-12),一个间隔时间(8-18/4)(/表示每隔4小时),一个列表(1,3,5),通配符。
更详细的分析,参考http://rainbowdesert.iteye.com/blog/2107220