【Spring】使用 @Schedule 完成定时任务

news/2024/9/20 6:52:43

在Spring框架中,使用Spring Schedule可以很方便地创建定时任务。以下是一个使用Spring Schedule完成定时任务的DEMO:

  1. 引入Spring Boot依赖:在pom.xml文件中添加Spring Boot Starter依赖,这会自动包含Spring Scheduling。
<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>
  1. 启用定时任务支持:在Spring Boot应用程序主类上添加@EnableScheduling注解。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class ScheduledTasksApplication {
    public static void main(String[] args) {
        SpringApplication.run(ScheduledTasksApplication.class, args);
    }
}
  1. 创建定时任务:创建一个带有@Scheduled注解的方法来定义任务。
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component
public class ScheduledTasks {

    private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Scheduled(fixedRate = 5000)
    public void scheduleTaskWithFixedRate() {
        System.out.println("固定时间任务 :: 执行时间 - " + dateTimeFormatter.format(LocalDateTime.now()));
    }

    @Scheduled(fixedDelay = 5000)
    public void scheduleTaskWithFixedDelay() {
        System.out.println("固定延迟任务 :: 执行时间 - " + dateTimeFormatter.format(LocalDateTime.now()));
    }

    @Scheduled(cron = "0 * * * * ?")
    public void scheduleTaskWithCronExpression() {
        System.out.println("计划任务 :: 执行时间 - " + dateTimeFormatter.format(LocalDateTime.now()));
    }
}

在上面的代码中:

  • @Scheduled(fixedRate = 5000):每5秒执行一次任务,不管上一次任务是否完成。
  • @Scheduled(fixedDelay = 5000):在上一次任务完成后等待5秒再执行下一次任务。
  • @Scheduled(cron = "0 * * * * ?"):使用Cron表达式在每分钟的第0秒执行任务。

完整的示例代码如下:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>spring-scheduled-tasks</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

ScheduledTasksApplication.java

package com.example.scheduledtasks;

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

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

ScheduledTasks.java

package com.example.scheduledtasks;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component
public class ScheduledTasks {

    private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Scheduled(fixedRate = 5000)
    public void scheduleTaskWithFixedRate() {
        System.out.println("固定时间任务 :: 执行时间 - " + dateTimeFormatter.format(LocalDateTime.now()));
    }

    @Scheduled(fixedDelay = 5000)
    public void scheduleTaskWithFixedDelay() {
        System.out.println("固定延迟任务 :: 执行时间 - " + dateTimeFormatter.format(LocalDateTime.now()));
    }

    @Scheduled(cron = "0 * * * * ?")
    public void scheduleTaskWithCronExpression() {
        System.out.println("计划任务 :: 执行时间 - " + dateTimeFormatter.format(LocalDateTime.now()));
    }
}

运行应用程序:

运行ScheduledTasksApplication主类,控制台输出定时任务的执行时间:

固定时间任务 :: 执行时间 - 2024-05-20 12:00:00
固定延迟任务 :: 执行时间 - 2024-05-20 12:00:05
计划任务 :: 执行时间 - 2024-05-20 12:01:00
...

这样完成了一个包含定时任务的程序。


http://lihuaxi.xjx100.cn/news/2178323.html

相关文章

Java日志体系概述

一. 日志体系分类 1.1 功能分类 1.2 jar包分类 二. 以log4j2为例 2.1 slf4j-api的初始化动态绑定过程 一. 日志体系分类 1.1 功能分类 门面类 slf4j&#xff1a;Simple Logging Facade for Java&#xff0c;为java提供的简单日志Facade具体实现类 logbacklog4j1log4j2jul&…

RAID配置实战

概念 raid磁盘阵列&#xff1a;可以用不同的硬盘分区&#xff0c;组成一个逻辑上的硬盘。具有高可用 raid级别&#xff1a; raid0 &#xff1a;条带化存储&#xff1a;数据分散在多个物理硬盘上的存储方式。利用多个磁盘并行读取和写入。存储性能和读写性能是最好的。没有冗…

【Linux系统】--- Linux内核日志等级详解

在编程的艺术世界里&#xff0c;代码和灵感需要寻找到最佳的交融点&#xff0c;才能打造出令人为之惊叹的作品。而在这座秋知叶i博客的殿堂里&#xff0c;我们将共同追寻这种完美结合&#xff0c;为未来的世界留下属于我们的独特印记。 【Linux系统】--- Linux内核日志等级详解…

python使用modbustcp协议与PLC进行简单通信

AI应用开发相关目录 本专栏包括AI应用开发相关内容分享&#xff0c;包括不限于AI算法部署实施细节、AI应用后端分析服务相关概念及开发技巧、AI应用后端应用服务相关概念及开发技巧、AI应用前端实现路径及开发技巧 适用于具备一定算法及Python使用基础的人群 AI应用开发流程概…

2024-5-29 石群电路-17

2024-5-29&#xff0c;星期三&#xff0c;17:26&#xff0c;天气&#xff1a;晴&#xff0c;心情&#xff1a;晴.今天又是阳光明媚的一天&#xff0c;没有什么特别的事情发生&#xff0c;给女朋友做了好吃的&#xff0c;吃了西瓜&#xff0c;加油学习&#xff0c;嘻嘻嘻~~~~ 今…

【Windows系统】使用robocopy移动文件

起因 笔记本机械革命Z2 Air&#xff0c;有2个固态m.2插口&#xff0c;和1个机械硬盘插口。但是机械硬盘插口线没有走线空间&#xff0c;都折在一起压在硬盘底下了&#xff0c;导致有时候机械硬盘读不出来。所以买了块国产的2Tm.2接口固态硬盘&#xff0c;用于存储机械硬盘的文…

折戟AI搜索,谷歌是否已死?

随着科技的飞速发展&#xff0c;人工智能&#xff08;AI&#xff09;技术已经渗透到我们生活的方方面面&#xff0c;搜索引擎作为互联网的重要入口&#xff0c;其变革也势不可挡。谷歌&#xff0c;作为全球最大的搜索引擎公司&#xff0c;近年来在AI领域的布局与投入备受关注。…

渗透测试框架之CobaltStrike,Metasploit域名上线隐藏IP

概述 为什么要隐藏IP 在拿下了目标机之后&#xff0c;目标机在内网里面&#xff0c;使用msf或者CS时&#xff0c;用自己的VPS做服务器的话&#xff0c;导致很容易被溯源。 域名上线原理 当我们访问域名时会经过域名解析 域名解析就是域名到IP地址的转换过程&#xff0c;那么…