Spring Boot 定时任务之@Schedule

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);
    }
}

结果

《Spring Boot 定时任务之@Schedule》

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

分析

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

《Spring Boot 定时任务之@Schedule》

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

参考

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

    原文作者:Spring Boot
    原文地址: https://blog.csdn.net/rickyit/article/details/77284064
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞