springboot定时任务

在 Spring Boot 中,定时任务是通过注解和配置轻松实现的。Spring Boot 提供了多种定时任务实现方式,最常见的是使用 @Scheduled 注解来配置定时任务。以下是 Spring Boot 中实现定时任务的几种方式及其使用方法。

1. 使用 @Scheduled 注解实现定时任务

@Scheduled 是 Spring 框架中用于声明定时任务的方法级别注解。通过在方法上添加该注解,你可以指定任务执行的时间间隔或执行时间。常见的几种方式有:固定频率执行、固定延迟执行以及使用 cron 表达式。

a. 基本配置

在 Spring Boot 中启用定时任务,只需要在主类或配置类上添加 @EnableScheduling 注解。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class MyApplication {
   
   
    public static void main(String[] args) {
   
   
        SpringApplication.run(MyApplication.class, args);
    }
}
b. @Scheduled 使用示例
  1. 固定速率执行任务(Fixed Rate)
    • @Scheduled(fixedRate = X):每隔 X 毫秒执行一次任务,任务开始时计算时间间隔,忽略任务执行所花的时间。
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class FixedRateTask {
   
   

    @Scheduled(fixedRate = 5000) // 每5秒执行一次
    public void performTask() {
   
   
        System.out.println("Fixed rate task executed at " + System.currentTimeMillis());
    }
}
  1. 固定延迟执行任务(Fixed Delay)
    • @Scheduled(fixedDelay = X):任务执行完成后,再等待 X 毫秒后再执行下一次任务。
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

翱翔-蓝天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值