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 复制代码
正在运行任务!!!
正在运行任务!!!
正在运行任务!!!
正在运行任务!!!
正在运行任务!!!
正在运行任务!!!

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

相关推荐
武子康1 小时前
Java-72 深入浅出 RPC Dubbo 上手 生产者模块详解
java·spring boot·分布式·后端·rpc·dubbo·nio
G_whang6 小时前
jenkins使用Jenkinsfile部署springboot+docker项目
spring boot·docker·jenkins
hac132210 小时前
Spring Boot 双数据源配置
java·spring boot·后端
凤山老林10 小时前
Spring Boot中的中介者模式:终结对象交互的“蜘蛛网”困境
java·spring boot·后端·设计模式·中介者模式
沃夫上校11 小时前
Spring Boot 中使用 Redis
spring boot·redis
java_强哥12 小时前
Spring Boot启动原理:从main方法到内嵌Tomcat的全过程
spring boot·后端·tomcat
李剑一12 小时前
上传三个参数,两个接收正常,一个死活都是null?
spring boot·后端
想要成为祖国的花朵15 小时前
Java_Springboot技术框架讲解部分(二)
java·开发语言·spring boot·spring
Q_Q51100828515 小时前
python的小学课外综合管理系统
开发语言·spring boot·python·django·flask·node.js
林邵晨16 小时前
Spring Boot 自带的 JavaMail 集成
spring boot·javamail