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

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

相关推荐
SoFlu软件机器人3 小时前
飞算 JavaAI 与 Spring Boot:如何实现微服务开发效率翻倍?
spring boot·后端·微服务
backRoads6 小时前
docker部署springboot(eureka server)项目
spring boot·docker·eureka
幽络源小助理6 小时前
SpringBoot民宿管理系统开发实现
java·spring boot·springboot·民宿系统
爱发飙的蜗牛6 小时前
springboot--web开发请求参数接收注解
java·spring boot·后端
BillKu6 小时前
Spring Boot + MyBatis 动态字段更新方法
java·spring boot·mybatis
橘猫云计算机设计7 小时前
springboot-基于Web企业短信息发送系统(源码+lw+部署文档+讲解),源码可白嫖!
java·前端·数据库·spring boot·后端·小程序·毕业设计
CopyLower7 小时前
Spring Boot的优点:赋能现代Java开发的利器
java·linux·spring boot
细心的莽夫7 小时前
Elasticsearch复习笔记
java·大数据·spring boot·笔记·后端·elasticsearch·docker
程序员阿鹏7 小时前
实现SpringBoot底层机制【Tomcat启动分析+Spring容器初始化+Tomcat 如何关联 Spring容器】
java·spring boot·后端·spring·docker·tomcat·intellij-idea
工业互联网专业10 小时前
基于JavaWeb的花店销售系统设计与实现
java·vue.js·spring boot·毕业设计·源码·课程设计·花店销售系统