码迷,mamicode.com
首页 > 编程语言 > 详细

Spring Scheduled实现定时任务

时间:2016-08-20 19:31:59      阅读:436      评论:0      收藏:0      [点我收藏+]

标签:

1 在.xml配置文件中引入命名空间

xmlns:task="http://www.springframework.org/schema/task" 
http://www.springframework.org/schema/task 
http://www.springframework.org/schema/task/spring-task-3.0.xsd"

2 设置自动发现

<task:annotation-driven/> 

3 在需要定时执行的方法上加上@Scheduled注解,一个实例如下:

@Service
public class AreaCacheService implements InitializingBean {

    Ehcache areaCache;

    @Override
    public void afterPropertiesSet() throws Exception {
        refresh();
    }

    @Scheduled(fixedDelay = 1000, initialDelay = 1000)
    public void refresh() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
        System.out.println(sdf.format(new Date()) + ": refresh cache...");
    }
}

以上例子让方法每次执行后都间隔一秒继续执行,执行结果如下:

20160820 17:54:47: refresh cache…
20160820 17:54:48: refresh cache…
20160820 17:54:49: refresh cache…
20160820 17:54:50: refresh cache…
20160820 17:54:51: refresh cache…
20160820 17:54:52: refresh cache…

注意:

Exactly one of the ‘cron’, ‘fixedDelay(String)’, or ‘fixedRate(String)’ attributes is required
(cron, fixdDelay, fixedRate三个属性必须设置一个)

属性含义:

属性 解释
cron A cron-like expression, extending the usual UN*X definition to include triggers on the second as well as minute, hour, day of month, month and day of week.
fixedDelay Execute the annotated method with a fixed period in milliseconds between the end of the last invocation and the start of the next.
fixedDelayString Execute the annotated method with a fixed period in milliseconds between the end of the last invocation and the start of the next.
fixedRate Execute the annotated method with a fixed period in milliseconds between invocations.
fixedRateString Execute the annotated method with a fixed period in milliseconds between invocations.
initialDelay Number of milliseconds to delay before the first execution of a fixedRate() or fixedDelay() task.
initialDelayString Number of milliseconds to delay before the first execution of a fixedRate() or fixedDelay() task.
zone A time zone for which the cron expression will be resolved.

也可以用配置文件来配置定时任务:

 <task:scheduled-tasks>   
        <task:scheduled ref="taskJob" method="job1" cron="0 * * * * ?"/>   
</task:scheduled-tasks>  

其中taskJob是对应的javaBean,job1是要定时执行的方法。

Spring Scheduled实现定时任务

标签:

原文地址:http://blog.csdn.net/foreverling/article/details/52262666

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!