Spring 中使用 @Scheduled 建立定时任务

1、定时任务触发条件

一、在 Application 启动类上添加:@EnableSchedulingjava

二、含定时方法的类上添加注解:@Component,该注解将定时任务类归入 spring bean 管理。spring

三、在定时方法上写上:@Scheduled(cron = "0 0/1 * * * ?"),该 cron 表达式为每一分钟执行一次方法。微信

2、@Scheduled用法

一、fixedDelay

@Scheduled(fixedDelay = 5000)
public void testFixedDelay(){
    try {
        log.info("当前时间:" + DateUtil.now());
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

每一个任务延迟3秒,而后打印当前时间。测试

fixedDelay规律总结:大数据

前一个任务执行结束后,再等待5秒,而后执行第二个任务。.net

二、fixedRate

@Scheduled(fixedRate = 5000)
public void testFixedRate(){
    try {
        log.info("当前时间:" + DateUtil.now());
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

任务启动后,每隔5秒执行一次任务。code

若是将延时时间修改成8秒,则输出变为8秒,以下图所示:blog

fixedRate规律总结:get

假如设置定时任务每5秒一执行,若是前一个任务用时超过了5秒,则等前一个任务完成后就马上执行第二次任务。若是前一个任务用时小于5秒,则等知足5秒之后,再执行第二次任务。io

三、Corn表达式详解(经常使用)

Corn 表达式可用 秒、分、时、天、周、月、年 来表示:

秒	分	时	天	周	月	年

0 * 14 * * ? *	: 表明天天从14点开始,每一分钟执行一次。
0 0 14 * * ? *	: 表明天天的14点执行一次任务。

可以使用 Corn 在线生成表达式:http://cron.qqe2.com/,来检测 Cron 的合理性。

**Corn 示例:**每2分钟执行一次。

@Scheduled(cron = "0 0/2 * * * ?")
public void test() {
    int j = 0;
    for (int i = 0; i < 10; i++) {
        log.info("Scheduled测试");
        j++;
        log.info("j的值为:" + j);
        try {
            Thread.sleep(1000 * 20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

效果:

总结

如上述代码所示,设置 test() 方法每2分钟执行一次。但若是前一个任务执行时长超过了2分钟,则第二个任务会等待前一个任务完成后的一段时间后再执行第二个任务。


本文来自: 微信公众号【大数据实战演练】。阅读更多精彩好文,欢迎关注微信公众号【大数据实战演练】。

相关文章
相关标签/搜索