首页 > 其他分享 >使用Spring Boot实现任务调度

使用Spring Boot实现任务调度

时间:2024-07-12 10:22:31浏览次数:13  
标签:Spring Boot springframework import org 任务调度 public

使用Spring Boot实现任务调度

大家好,我是微赚淘客系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!

在日常开发中,任务调度是一个非常常见的需求,例如定时清理日志、定时备份数据、定时发送通知等。Spring Boot提供了强大的任务调度功能,可以方便地实现定时任务。本文将详细介绍如何使用Spring Boot实现任务调度,包括基本配置、定时任务的定义和常见问题的解决。

1. 创建Spring Boot项目

首先,创建一个Spring Boot项目,选择以下依赖项:

  • Spring Web
  • Spring Boot DevTools

项目创建完成后,项目结构如下:

src/
|-- main/
|   |-- java/
|   |   `-- cn/
|   |       `-- juwatech/
|   |           `-- scheduler/
|   |               |-- SchedulerApplication.java
|   |               `-- tasks/
|   |                   `-- ScheduledTasks.java
|   `-- resources/
|       `-- application.properties

2. 配置任务调度

application.properties文件中,可以进行一些基本的配置。例如,配置任务调度的线程池:

spring.task.scheduling.pool.size=10

3. 启用任务调度

在主应用程序类中启用任务调度功能。创建SchedulerApplication类:

package cn.juwatech.scheduler;

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

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

4. 定义定时任务

接下来,创建一个类来定义定时任务。创建ScheduledTasks类:

package cn.juwatech.scheduler.tasks;

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("Fixed Rate Task :: Execution Time - " + dateTimeFormatter.format(LocalDateTime.now()));
    }

    @Scheduled(fixedDelay = 7000)
    public void scheduleTaskWithFixedDelay() {
        System.out.println("Fixed Delay Task :: Execution Time - " + dateTimeFormatter.format(LocalDateTime.now()));
    }

    @Scheduled(cron = "0 * * * * ?")
    public void scheduleTaskWithCronExpression() {
        System.out.println("Cron Task :: Execution Time - " + dateTimeFormatter.format(LocalDateTime.now()));
    }
}

在这个示例中,定义了三个定时任务:

  • scheduleTaskWithFixedRate:每5秒执行一次。
  • scheduleTaskWithFixedDelay:上一个任务完成后延迟7秒执行。
  • scheduleTaskWithCronExpression:每分钟的第0秒执行。

5. 运行和测试

启动Spring Boot应用程序,观察控制台输出,可以看到定时任务按预期时间间隔执行。

6. 常见问题解决

  • 任务冲突:如果多个任务需要共享资源,可能会出现任务冲突的情况。可以使用synchronized关键字或锁机制来解决。
  • 任务失败处理:如果任务在执行过程中失败,可以使用重试机制或任务失败记录日志以便后续处理。
  • 任务调度器配置:可以根据需要配置任务调度器的线程池大小、队列容量等参数,以提高任务调度的性能。

7. 高级任务调度

Spring Boot还支持更高级的任务调度功能,例如:

  • 异步任务:使用@Async注解实现异步任务执行。
  • 动态任务调度:根据业务需求动态调整任务调度时间。

异步任务示例

ScheduledTasks类中,定义一个异步任务:

package cn.juwatech.scheduler.tasks;

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

import java.util.concurrent.CompletableFuture;

@Component
public class ScheduledTasks {

    @Async
    @Scheduled(fixedRate = 10000)
    public CompletableFuture<Void> asyncTask() {
        System.out.println("Async Task :: Execution Time - " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        return CompletableFuture.completedFuture(null);
    }
}

动态任务调度示例

可以使用Spring的TaskScheduler接口实现动态任务调度:

package cn.juwatech.scheduler.tasks;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.Instant;

@Component
public class DynamicScheduledTasks {

    @Autowired
    private TaskScheduler taskScheduler;

    @PostConstruct
    public void scheduleRunnableWithCronTrigger() {
        Runnable task = () -> System.out.println("Dynamic Task :: Execution Time - " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        taskScheduler.schedule(task, new CronTrigger("0 * * * * ?"));
    }
}

8. 完整代码示例

以下是整个项目的代码结构及内容:

application.properties

spring.task.scheduling.pool.size=10

SchedulerApplication.java

package cn.juwatech.scheduler;

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

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

ScheduledTasks.java

package cn.juwatech.scheduler.tasks;

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("Fixed Rate Task :: Execution Time - " + dateTimeFormatter.format(LocalDateTime.now()));
    }

    @Scheduled(fixedDelay = 7000)
    public void scheduleTaskWithFixedDelay() {
        System.out.println("Fixed Delay Task :: Execution Time - " + dateTimeFormatter.format(LocalDateTime.now()));
    }

    @Scheduled(cron = "0 * * * * ?")
    public void scheduleTaskWithCronExpression() {
        System.out.println("Cron Task :: Execution Time - " + dateTimeFormatter.format(LocalDateTime.now()));
    }
}

通过以上步骤,我们成功地在Spring Boot项目中实现了任务调度,并演示了如何配置和使用定时任务。通过这种方式,我们可以轻松地实现各种定时任务,满足不同的业务需求。

著作权归聚娃科技微赚淘客系统开发者团队,转载请注明出处!

标签:Spring,Boot,springframework,import,org,任务调度,public
From: https://www.cnblogs.com/szk123456/p/18297709

相关文章

  • 使用Spring Boot实现文件上传功能
    使用SpringBoot实现文件上传功能大家好,我是微赚淘客系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!在这篇文章中,我们将详细介绍如何使用SpringBoot实现文件上传功能。这是一个常见的需求,无论是处理用户上传的图片、文档,还是其他类型的文件,了解并掌握文件上传的实现是非常......
  • 基于java+springboot+vue实现的在线教育系统(文末源码+Lw)111
    基于SpringBoot+Vue的实现的在线教育系统(源码+数据库+万字Lun文+流程图+ER图+结构图+演示视频+软件包)系统功能:本在线教育系统管理员功能有个人中心,用户管理,讲师管理,普通管理员管理,课程管理员管理,课程管理,课程分类管理,教师管理,名师管理,系统管理,订单管理。普通管理员和课程......
  • 基于java+springboot+vue实现的作业管理系统(文末源码+Lw)110
    基于SpringBoot+Vue的实现的作业管理系统(源码+数据库+万字Lun文+流程图+ER图+结构图+演示视频+软件包)功能描述:作业管理系统有管理员,教师,学生三个角色。教师和学生都可以进行注册然后再登录。学生可以修改自己的密码,查看和下载作业信息,并且可以提交自己写好的作业,并且可以......
  • SpringBoot2.6.13版本引入Swagger
    1.引入依赖<!--https://mvnrepository.com/artifact/io.springfox/springfox-swagger2--><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>3.0.0</version&g......
  • 缓存框架-Spring Cache基本用法
    一、概述SpringCache是一个框架,实现了基于注解的缓存功能,只需要简单地加一个注解,就能实现缓存功能。SpringCache提供了一层抽象,底层可以切换不同的缓存实现,例如:EHCacheCaffeineRedis(常用)二、环境准备1、导入Redis和SpringCache依赖<dependency><groupId......
  • 【SpringBoot框架】-- 快速入门
    目录1.spring简介1.1springboot快速入门1.1.1开发步骤1.1.2创建项目2.springboot的特点3.配置文件种类4.读取配置文件中的内容4.1 @ConfigurationPropertie4.2  @Value5.profile多环境配置 6.springboot注册web组件7.springboot包扫描的原理8.spr......
  • Java毕业设计基于Vue+SpringBoot的博物馆展览与服务一体化平台(代码+数据库+文档LW+运
    文末获取资源,收藏关注不迷路文章目录前言主要使用技术研究内容核心代码文章目录前言博物馆展览与服务一体化,其工作流程繁杂、多样、管理复杂与设备维护繁琐。而计算机已完全能够胜任博物馆展览与服务一体化工作,而且更加准确、方便、快捷、高效、清晰、透明,它完全......
  • Java毕业设计基于Vue+SpringBoot的单位公司员工考勤签到系统(代码+数据库+文档LW+运行
    文末获取资源,收藏关注不迷路文章目录前言主要使用技术研究内容核心代码文章目录前言当今社会已经步入了科学技术进步和经济社会快速发展的新时期,国际信息和学术交流也不断加强,计算机技术对经济社会发展和人民生活改善的影响也日益突出,人类的生存和思考方式也产生......
  • Java毕业设计基于Vue+SpringBoot的厨房达人美食分享平台(代码+数据库+文档LW+运行成功
    文末获取资源,收藏关注不迷路文章目录前言主要使用技术研究内容核心代码文章目录前言厨房达人美食分享平台的目的是让使用者可以更方便的将人、设备和场景更立体的连接在一起。能让用户以更科幻的方式使用产品,体验高科技时代带给人们的方便,同时也能让用户体会到与......
  • day01-Spring
    学习目标能够说出Spring的体系结构能够编写IOC入门案例能够编写DI入门案例能够配置setter方式注入属性值能够配置构造方式注入属性值能够理解什么是自动装配一、Spring简介1Spring课程介绍问题导入我们为什么要学习Spring框架?1.1为什么要学Spring技术是Java......