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

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

相关推荐
KK溜了溜了22 分钟前
JAVA-springboot log日志
java·spring boot·logback
我命由我123451 小时前
Spring Boot 项目集成 Redis 问题:RedisTemplate 多余空格问题
java·开发语言·spring boot·redis·后端·java-ee·intellij-idea
面朝大海,春不暖,花不开1 小时前
Spring Boot消息系统开发指南
java·spring boot·后端
hshpy1 小时前
setting up Activiti BPMN Workflow Engine with Spring Boot
数据库·spring boot·后端
jay神2 小时前
基于Springboot的宠物领养系统
java·spring boot·后端·宠物·软件设计与开发
不知几秋2 小时前
Spring Boot
java·前端·spring boot
howard20053 小时前
5.4.2 Spring Boot整合Redis
spring boot·整合redis
TracyCoder1233 小时前
接口限频算法:漏桶算法、令牌桶算法、滑动窗口算法
spring boot·spring·限流
饮长安千年月4 小时前
JavaSec-SpringBoot框架
java·spring boot·后端·计算机网络·安全·web安全·网络安全
考虑考虑5 小时前
Jpa中的@ManyToMany实现增删
spring boot·后端·spring