当前位置: 首页 > news >正文

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;</

http://www.mrgr.cn/news/52620.html

相关文章:

  • C#笔记(1)
  • “ps“指的是皮秒(picosecond)
  • 如何克服解决 Git 冲突的恐惧症
  • 【时时三省】(C语言基础)函数介绍strcmp
  • 限流是什么?如何限流?怎么限流?
  • Java interface 接口的巧妙应用:让你的代码更优雅
  • 图论刷题
  • 【算法】约瑟夫环问题
  • 期货配资系统风控逻辑开发/完整源代码
  • Oracle Expdp按条件导出-指定表数据
  • 【Vue】Vue(八)Vue3.0 使用ref 和 reactive创建响应式数据
  • 单点登录的要点
  • 终端 数据表格
  • 基于SSM的个性化商铺系统【附源码】
  • MAC 电脑Office power point编辑的时候,显示“某些字体无法随演示文稿一起保存,仍然要保存演示文稿吗?”
  • 【哈工大_操作系统理论】L2223 多级页表与快表段页结合的实际内存管理
  • React1-基础概念
  • 【c++篇】:初识c++--编程新手的快速入门之道(二)
  • 【C++】—— list迭代器
  • 看《米小圈日记魔法》突破写作困境一点也不难!