【SpringBoot】 “@Scheduled” 定时任务

目录

一、使用注解@EnableScheduling

二、创建任务类,定义@Component 组件

三、Cron表达式(来源于网络)


一、使用注解@EnableScheduling

在application启动类,加上@EnableScheduling 注解,Spring Boot 会会自动扫描任务类,开启定时任务。

/**
 * @author h
 */
// 扫描 所有需要的包, 包含一些自用的工具类包 所在的路径
@ComponentScan(basePackages = {"com.example"})
// 开启定时任务
@EnableScheduling
// 开启异步调用方法
@EnableAsync

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

说明:

1、@EnableScheduling 为开启定时任务。

2、@ComponentScan 定义扫描包的路径。

二、创建任务类,定义@Component 组件

创建com.weiz.tasks包,在tasks包里增加TestTask任务类,加上@Component 注解,那么TestTask就会作为组件被容器扫描到。扫描到之后,Spring Boot容器就会根据任务类里面定义的时间,定时执行了。

/**
 * @author Gong XiuYi
 * @date 2022/2/22 15:10
 **/
@Component
public class TestTask {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    /**
     * 定义每过3秒执行任务
     * 系统每隔3s,会打印系统时间
     * */
    @Scheduled(fixedRate = 3000)
// @Scheduled(cron = "4-40 * * * * ?")
    public void reportCurrentTime() {
        System.out.println("现在时间:" + dateFormat.format(new Date()));
    }
}

说明:@Scheduled 是定时任务执行的时间,可以每个一段时间执行,也可以使用cron 表达式定义执行时间。

三、Cron表达式(来源于网络)

Spring Boot 定时任务支持每个一段时间执行或是使用cron 表达式定义执行时间

Cron格式

Cron表达式被用来配置CronTrigger实例。Cron表达式是一个由6,7个域(子表达式)和空格组成的字符串。每个子表达式都描述了一个单独的日程细节

是否强制

允许值

允许特殊字符

Seconds

YES

0-59

, - * /

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值