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

结果

这里写图片描述

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

分析

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

这里写图片描述

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

参考

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

  • 6
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值