Spring Boot 定时任务之@Schedule

2017/08/18

The @Scheduled annotation can be added to a method along with trigger metadata.

概念

项目经常会用到定时任务,实现定时任务的方式有很多种,参考Spring定时任务的几种实现。在Spring框架中,实现定时任务很简单。常用的实现方式是使用注解@Schedule

@Schedule 常用来实现简单的定时任务。例如凌晨1点跑批,每1小时更新订单状态等。

代码

官网给出简单的例子。

具体的任务类

@Component
public class ScheduleTask {
    @Scheduled(cron = "0/1 * * * * ?")
    public void printSay() {
        System.out.println("This is a say method!"+new Date());
    }
}

Application:

@SpringBootApplication
@EnableScheduling
public class Application {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class);
    }
}

结果

这里写图片描述

注意表达式一定要正确,不然结果出不来的。

分析

@Scheduled注解必须要有,可以指定cron表达式,当然也可以指定其他选项。看源码:

这里写图片描述

@EnableScheduling 确保后台任务进程被创建。

参考

34.4.2 The @Scheduled annotation Spring定时任务的几种实现 Scheduling Tasks springBoot中@Scheduled执行原理解析


作者:Wuxinshui
出处:http://wuxinshui.github.io
版权归作者所有,转载请注明出处

Post Directory