springboot定时任务 @Scheduled

在Spring框架中,可以使用@Scheduled注解来创建定时任务。要每隔一秒钟执行一次任务,需要使用cron表达式或fixedRate参数来配置定时任务。

使用 @Scheduled 注解

  1. 添加依赖:确保在项目的pom.xml(对于Maven)或build.gradle(对于Gradle)中添加了Spring的调度任务依赖。

    Maven:

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

    Gradle:

    implementation 'org.springframework.boot:spring-boot-starter'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-task'
    
  2. 启用定时任务:在主应用类上添加@EnableScheduling注解。

  3. 创建定时任务方法:在任意Spring管理的bean中创建一个使用@Scheduled注解的方法。

代码示例

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

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

@Component
class ScheduledTasks {
    @Scheduled(fixedRate = 1000)
    public void performTask() {
        System.out.println("Task executed at: " + System.currentTimeMillis());
    }
}

说明

  • @EnableScheduling:启用Spring的调度任务。
  • @Scheduled(fixedRate = 1000):每隔1000毫秒(1秒)执行一次任务。fixedRate表示从任务开始时间开始计时。
  • performTask():定时任务执行的方法。此方法将在每次调度时执行。

可选配置

可以根据具体需求,使用不同的调度参数:

  • fixedDelay:上一个任务完成后等待固定时间再执行下一次任务。
  • initialDelay:在应用启动后,延迟指定时间再开始执行第一次任务。
  • cron:使用cron表达式配置复杂的调度规则。

示例

// 使用cron表达式每秒执行一次
@Scheduled(cron = "*/1 * * * * *")
public void performTaskWithCron() {
    System.out.println("Task executed with cron at: " + System.currentTimeMillis());
}

// 使用fixedDelay在上一个任务完成后等待1000毫秒再执行下一次
@Scheduled(fixedDelay = 1000)
public void performTaskWithFixedDelay() {
    System.out.println("Task executed with fixed delay at: " + System.currentTimeMillis());
}

// 使用initialDelay在应用启动后延迟5秒执行第一次,然后每隔1秒执行一次
@Scheduled(initialDelay = 5000, fixedRate = 1000)
public void performTaskWithInitialDelay() {
    System.out.println("Task executed with initial delay at: " + System.currentTimeMillis());
}

下一步建议:
a. 使用 cron 表达式配置复杂的定时任务规则。
b. 添加日志记录,监控任务的执行情况和性能。

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值