Spring Mvc中使用Task实现定时任务,以及遇到的一个问题

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

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

在xsi:schemaLocation中加入

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

同时加入

1 xmlns:task="http://www.springframework.org/schema/task

第二步,开启task注解

1 <task:annotation-driven/>

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

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

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

 

posted on 2017-02-22 14:41  FlyHeLanMan  阅读(2321)  评论(0编辑  收藏  举报

导航