SpringBoot定时任务

SpringBoot定时任务

在我们开发项目过程中,经常需要定时任务来帮助我们来做一些内容, Spring Boot 默认已经帮我们实行了,只需

要添加相应的注解就可以实现。

常用的定时任务有两种:

  • 1、基于注解

  • 2、基于接口

1、基于注解@Scheduled

1.1 pom依赖

pom 包里面只需要引入 Spring Boot Starter 包即可

xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
        <relativePath/>
    </parent>

    <groupId>com.example</groupId>
    <artifactId>spring-boot-scheduler</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-scheduler</name>
    <description>spring-boot-scheduler</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

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

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

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

</project>

1.2 启动类启用定时

在启动类上面加上@EnableScheduling即可开启定时

java 复制代码
package com.example;

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

@SpringBootApplication
@EnableScheduling
public class Application {

    public static void main(String[] args) {

        SpringApplication.run(Application.class, args);
    }

}

1.3 配置文件

properties 复制代码
spring.application.name=spring-boot-scheduler

1.4 创建定时任务实现类

定时任务1:

java 复制代码
package com.example.task;

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

@Component
public class SchedulerTask {

    private int count = 0;

    @Scheduled(cron = "*/6 * * * * ?")
    private void process() {
        System.out.println("this is scheduler task runing  " + (count++));
    }

}

定时任务2:

java 复制代码
package com.example.task;

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

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class Scheduler2Task {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 6000)
    public void reportCurrentTime() {

        System.out.println("现在时间:" + dateFormat.format(new Date()));
    }

}

结果如下:

elixir 复制代码
现在时间:10:33:59
this is scheduler task runing  0
现在时间:10:34:05
this is scheduler task runing  1
现在时间:10:34:11
this is scheduler task runing  2
现在时间:10:34:17
this is scheduler task runing  3
现在时间:10:34:23
this is scheduler task runing  4

1.5 参数说明

@Scheduled 参数可以接受两种定时的设置,一种是我们常用的cron="*/6 * * * * ?",一种是

fixedRate = 6000,两种都表示每隔六秒打印一下内容。

fixedRate 说明

  • @Scheduled(fixedRate = 6000) :上一次开始执行时间点之后6秒再执行,若上次任务执行时间超过6秒,

    则立即执行。

  • @Scheduled(fixedDelay = 6000) :上一次执行完毕时间点之后6秒再执行。

  • @Scheduled(initialDelay=1000, fixedRate=6000) :第一次延迟1秒后执行,之后按 fixedRate 的规

    则每6秒执行一次。

cron说明

  • @Scheduled(cron = "0 0 1 * * ?"):每天凌晨1点执行

  • @Scheduled(cron = "*/6 * * * * ?"):每6秒执行一次

不会写corn表达式的小伙伴,可以使用https://cron.qqe2.com ,会帮你自动生成corn表达式,且能

检测你的表达式是否合法,非常好用!

2、基于接口形式的定时任务

基于注解的方式的任务配置起来很简单也很好用,但是由于不能传递参数,使用场景有限。那么就需要使用基于接

口形式的定时任务了。

2.1 pom依赖

xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.6</version>
        <relativePath/>
    </parent>

    <groupId>com.schedule</groupId>
    <artifactId>spring-boot-scheduler1</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-scheduler1</name>
    <description>SprintBoot定时任务</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

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

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

    </dependencies>

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

</project>

2.2 启动类

java 复制代码
package com.schedule;

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

@EnableScheduling
@SpringBootApplication
public class SpringBootScheduleApplication {

    public static void main(String[] args) {

        SpringApplication.run(SpringBootScheduleApplication.class, args);
    }

}

2.3 定时任务类

java 复制代码
package com.schedule;

import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

/**
 * @author zhangshixing
 * @date 2021年10月30日 22:01
 */
@Component
public class SchedulingService implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(
                new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("正在运行任务!!!");
                    }
                },
                triggerContext -> {
                    return new CronTrigger("0/1 * * * * ? ").nextExecutionTime(triggerContext);
                }
        );
    }
}
elixir 复制代码
正在运行任务!!!
正在运行任务!!!
正在运行任务!!!
正在运行任务!!!
正在运行任务!!!
正在运行任务!!!

以上就是两种常用的定时任务。

相关推荐
IT毕设实战小研1 小时前
基于Spring Boot 4s店车辆管理系统 租车管理系统 停车位管理系统 智慧车辆管理系统
java·开发语言·spring boot·后端·spring·毕业设计·课程设计
一只爱撸猫的程序猿2 小时前
使用Spring AI配合MCP(Model Context Protocol)构建一个"智能代码审查助手"
spring boot·aigc·ai编程
甄超锋2 小时前
Java ArrayList的介绍及用法
java·windows·spring boot·python·spring·spring cloud·tomcat
武昌库里写JAVA5 小时前
JAVA面试汇总(四)JVM(一)
java·vue.js·spring boot·sql·学习
Pitayafruit6 小时前
Spring AI 进阶之路03:集成RAG构建高效知识库
spring boot·后端·llm
zru_96026 小时前
Spring Boot 单元测试:@SpyBean 使用教程
spring boot·单元测试·log4j
甄超锋6 小时前
Java Maven更换国内源
java·开发语言·spring boot·spring·spring cloud·tomcat·maven
还是鼠鼠7 小时前
tlias智能学习辅助系统--Maven 高级-私服介绍与资源上传下载
java·spring boot·后端·spring·maven
舒一笑12 小时前
Started TttttApplication in 0.257 seconds (没有 Web 依赖导致 JVM 正常退出)
jvm·spring boot·后端
javadaydayup13 小时前
Apollo 凭什么能 “干掉” 本地配置?
spring boot·后端·spring