springboot整合定时器

本文介绍了如何在Spring Boot应用中使用Spring Boot Starter Quartz实现定时任务,如定时删除OSS的冗余文件和自动取消未支付订单。通过引入依赖、编写定义任务的组件类,并配置定时执行的cron表达式,展示了实际操作步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.什么是定时器?

在指定的时间,执行相应的业务代码。

2.为什么使用定时器?

比如: OSS文件系统服务器,会产生大量冗余文件。定时删除冗余文件【凌晨2~3点】。

比如: 下单后半个未支付--取消订单

(1)导入定时器依赖

        

        <dependency>
                 <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-quartz</artifactId>
        </dependency>

(2)编写定义任务代码



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @program: qy151-springboot
 * @description:
 * @create: 2022-07-25 14:20
 **/
@Component //该类交于spring容器来管理
public class QuartzTask {


    //任务代码cron:定义定时任务的规则 https://www.pppet.net/
    @Scheduled(cron = "0/1 * * * * ?")
    public void task01(){
        System.out.println("业务代码");
    }
}

(3) 开启定时任务的注解

 (4)测试


package com.xzh.config;
 
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component//该类交于spring容器来管理
public class QuartzTest {
 
 
    @Scheduled(cron = "0/1 * * * * ? ") //定时器注解 任务代码cron  规则网址https://www.pppet.net/
    public void Test01(){
        System.out.println("执行定时器任务代码段");
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值