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 号。
问号(?):仅用于日期和星期几字段,表示不指定具体值。通常用于避免冲突。
注意事项
- 确保你的定时任务是线程安全的,尤其是在涉及共享资源时。
- 配置文件中,你可以调整线程池大小,默认情况下,Spring使用单一的线程来执行调度任务。
spring:
task:
scheduling:
pool:
size: 5 # 设置线程池大小
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)