SpringMvc中使用Task实现定时任务

Spring中实现定时任务其实很简单,可以使用spring中自带的task 相当于轻量级的Quartz,并且spring 3.0 之后支持注解的方式,使用起来非常简单,方便,具体实现如下:

第一步,修改spring.xml配置文件

在xsi:schemaLocation中加入

http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd

同时加入

xmlns:task=”http://www.springframework.org/schema/task

第二步,开启task注解

1 task:annotation-driven/

第三步,编写作业类,并在作业类中加入注解

1
2
3
4
5
6
7
8
9
@Component("myTask") 
@Lazy(false)
public class MyTask {
@Scheduled(cron="0/5 * * * * ?")
public void run(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(new Date()) + "定时任务执行");
}
}

注意:使用Lazy注解是因为spring 配置文件采用懒加载的原因default-lazy-init=”true” 这个配置会导致 @Scheduled失效