SpringBoot-定时任务

SpringBoot-定时任务

在Spring Boot中实现定时任务相对简单,主要可以通过使用@Scheduled注解来完成。

添加依赖:确保你的pom.xml中包含Spring Boot Starter。通常情况下,Spring Boot Web Starter已经包含了所需的依赖。

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

启用调度功能:在Spring Boot应用的主类或任意配置类上添加@EnableScheduling注解,以启用调度功能。

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

@SpringBootApplication  
@EnableScheduling    //启用调度功能
public class MySpringBootApplication {  
    public static void main(String[] args) {  
        SpringApplication.run(MySpringBootApplication.class, args);  
    }  
}  

创建定时任务:你可以在任何一个Spring管理的bean中创建带有@Scheduled注解的方法。

import org.springframework.scheduling.annotation.Scheduled;  
import org.springframework.stereotype.Component;  

@Component  
public class ScheduledTasks {  

    @Scheduled(fixedRate = 5000) // 每5000毫秒执行一次  
    public void reportCurrentTime() {  
        System.out.println("当前时间:" + new java.util.Date());  
    }  

    @Scheduled(cron = "0 0/1 * * * ?") // 每分钟的第0秒触发  
    public void executeTask() {  
        System.out.println("执行定时任务:" + new java.util.Date());  
    }  
}  

方法说明

  • @Scheduled(fixedRate = 5000):表示每隔5000毫秒调用一次此方法(从上次开始计时)。
  • @Scheduled(fixedDelay = 5000):表示在方法执行完成后的5000毫秒后再调用此方法。
  • @Scheduled(cron = "0 0/1 * * * ?"):使用cron表达式定义更复杂的定时计划,这里表示每分钟的开始时刻执行。
  • cron 表达式:自动生成网站===》https://cron.ciding.cc/

SpringBoot中的cron表达式语法如下

┌───────────── second (0-59)
│ ┌───────────── minute (0 - 59)
│ │ ┌───────────── hour (0 - 23)
│ │ │ ┌───────────── day of the month (1 - 31)
│ │ │ │ ┌───────────── month (1 - 12) (or JAN-DEC)
│ │ │ │ │ ┌───────────── day of the week (0 - 7)
│ │ │ │ │ │          (0 or 7 is Sunday, or MON-SUN)
│ │ │ │ │ │
* * * * * *

    
星号(*):表示匹配任意值。例如,* 在分钟字段中表示每分钟都执行。
逗号(,):用于分隔多个值。例如,1,3,5 在小时字段中表示 1 点、3 点和 5 点执行。
斜线(/):用于指定间隔值。例如,*/5 在分钟字段中表示每 5 分钟执行一次。
连字符(-):用于指定范围。例如,10-20 在日期字段中表示从 10 号到 20 号。
问号(?):仅用于日期和星期几字段,表示不指定具体值。通常用于避免冲突。

注意事项

  1. 确保你的定时任务是线程安全的,尤其是在涉及共享资源时。
  2. 配置文件中,你可以调整线程池大小,默认情况下,Spring使用单一的线程来执行调度任务。
spring:  
  task:  
    scheduling:  
      pool:  
        size: 5  # 设置线程池大小
posted @   CH_song  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示