SpringBoot开启定时任务——Spring Task

本文介绍了如何在SpringBoot中使用@Scheduled注解创建定时任务,包括将类交给Spring管理、设置Cron表达式(如使用在线生成工具),以及在启动类上启用定时任务功能,以OrderStatisticsTask为例详细说明.
摘要由CSDN通过智能技术生成

1.在需要进行定时任务的方法上加上注解@Scheduled,并且将类交给Spring容器管理,并给cron属性赋值,cron表示可以从网上找一个在线生成的网站,不用自己编写。

值得注意的是,网站生成的可能会有7位,而在SpringBoot中cron表达式中只能有6位,因为SpringBoot中的定时任务是不支持跨年的。

Cron在线表达式生成器

2.在启动类上添加@EnableScheduling注解开启定时任务功能

@Component
@RequiredArgsConstructor
public class OrderStatisticsTask {

    private final OrderStatisticsMapper orderStatisticsMapper;
    private final OrderInfoMapper orderInfoMapper;
    //每天的凌晨两点,查询前一天的统计数据,把统计之后的数据添加到统计结果表中
    @Scheduled(cron = "0 0 2 * * ?")
    public void orderTotalAmountStatistics() {
        String createTime = DateUtil.offsetDay(new Date(), -1).toString(new SimpleDateFormat("yyyy-MM-dd"));
        OrderStatistics orderStatistics = orderInfoMapper.selectOrderStatistics(createTime);
        if(orderStatistics != null) {
            orderStatisticsMapper.insert(orderStatistics) ;
        }
    }

}

  • 8
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值