Spring Boot的定时任务与异步任务

简介: Spring Boot的定时任务与异步任务

【第一部分】历史文章:
SpringBoot总结(一)——第一个SpringBoot项目
SpringBoot总结(二)——Spring Boot的自动配置
SpringBoot总结(三)——SpringBoot的配置文件
SpringBoot总结(四)——@Value和@ConfigurationProperties的区别
SpringBoot总结(五)——@PropertySource注解与@ImportResource注解
SpringBoot总结(六)——SpringBoot配置文件占位符
SpringBoot总结(七)——Profile的使用
SpringBoot总结(八)——配置文件的加载位置
SpringBoot总结(九)——@Conditional注解与自动配置报告
SpringBoot总结(十)——SpringBoot+Mybatis实现数据库的CRUD(从创建到实现【超详细附代码】)
SpringBoot总结(十一)——SpringBoot的静态资源映射规则
SpringBoot总结(十二)——登录界面的实现
SpringBoot总结(十三)——修改嵌入式Servlet容器配置
SpringBoot总结(十四)——SpringBoot整合JDBCTemplate及Druid连接池
SpringBoot总结(十五)——接口架构风格(RESTful)
SpringBoot总结(十六)——Spring Boot的邮件发送


# Spring Boot的定时任务与异步任务 下面以简单的例子介绍Spring Boot的定时任务与异步任务:
# 前言 定时任务是企业级开发中的最常见的功能之一,例如:统计订单数、数据库的备份、定时发送短信和邮件、定时统计博客访客等;简单的定时任务可以通过Spring中的 `@Scheduled`注解来实现;而复杂的定时任务可以通过Quartz来实现。
# 一、定时任务 `@Scheduled`是由Spring提供的定时任务注解,使用较为方便、配置简单,可以很好的解决大部分的定时任务需求。 下面进行简单介绍定时任务的使用: ## 1.创建项目 创建一个Spring Boot的Web工程,具体创建过程这里不再介绍。 ## 2.开启定时任务 在项目的启动类上加上`@EnableScheduling` 注解来开启定时任务。 ```java package com.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; /** * @author */ @EnableScheduling @SpringBootApplication public class SpringbootTaskApplication { public static void main(String[] args) { SpringApplication.run(SpringbootTaskApplication.class, args); } } ``` ## 3.配置定时任务 注:定时任务主要通过 `@Scheduled`注解来进行配置,示例代码如下所示: ```java package com.example.service; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import java.util.Date; /** * @author */ @Service public class ScheduledService { @Scheduled(fixedDelay = 1000) public void scheduledTask1(){ System.out.println("fixedDelay:"+new Date()); } @Scheduled(fixedRate = 2000) public void scheduledTask2(){ System.out.println("fixedRate:"+new Date()); } @Scheduled(initialDelay = 1000,fixedRate = 2000) public void scheduledTask3(){ System.out.println("initialDelay:"+new Date()); } @Scheduled(cron = "0 * * * * ?") public void scheduledTask4(){ System.out.println("cron:"+new Date()); } } ``` 注: - `@Scheduled`注解来标注一个定时任务。 - fixedDelay=1000表示:`在当前任务执行结束1秒后开启另外一个任务`。 - fixedRate=2000表示:`当前任务开始执行2秒后开启另外一个定时任务`。 - initialDelay=1000表示:`首次执行的延迟时间`。 - 在@Scheduled注解中也可以使用cron表达式。 - 表达式:cron = "0 * * * * ?"表示`该定时任务每分钟执行一次`。 启动项目,控制台打印如下: ![在这里插入图片描述](https://ucc.alicdn.com/images/user-upload-01/2020102821392019.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80Mzc1OTM1Mg==,size_16,color_FFFFFF,t_70#pic_center) # 二、异步任务 两个注解: - `@EnableAsync` 开启异步注解功能 - `@Async` 一般用在类的方法上;若用在类上,表示这个类的所有的方法都是异步执行。 ## 1.开启异步任务 在项目的启动类上加上`@EnableAsync` 注解。 ```java package com.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; /** * @author */ @EnableAsync @EnableScheduling @SpringBootApplication public class SpringbootTaskApplication { public static void main(String[] args) { SpringApplication.run(SpringbootTaskApplication.class, args); } } ``` ## 2.简单使用示例 ```java package com.example.task; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; /** * @author */ @Component public class AsyncTask { @Async public void Task1() throws Exception{ long start = System.currentTimeMillis(); Thread.sleep(1000); long end = System.currentTimeMillis(); System.out.println("task1耗时:"+(end-start)+"毫秒!"); } public void Task2() throws Exception{ long start = System.currentTimeMillis(); Thread.sleep(2000); long end = System.currentTimeMillis(); System.out.println("task2耗时:"+(end-start)+"毫秒!"); } public void Task3() throws Exception{ long start = System.currentTimeMillis(); Thread.sleep(3000); long end = System.currentTimeMillis(); System.out.println("task3耗时:"+(end-start)+"毫秒!"); } } ``` ## 3.测试 ```java @GetMapping("/asynctasktest") public String AsyncTaskTest() throws Exception { long start = System.currentTimeMillis(); asyncTask.Task1(); asyncTask.Task2(); asyncTask.Task3(); long end = System.currentTimeMillis(); System.out.println("全部完成一共耗时:" + (end - start) + "毫秒"); return "执行完成!!!"; } ```
# 总结 以上分别介绍了Spring Boot的定时任务与异步任务,以及用简单的示例进行了演示。希望通过以上例子能给予大家帮助。😊 关于本项目的示例代码获取方式:关注+私信并回复:【定时任务与异步任务】即可获取哦!!!
相关文章
|
2月前
|
Java 开发者 Spring
【SpringBoot 异步魔法】@Async 注解:揭秘 SpringBoot 中异步方法的终极奥秘!
【8月更文挑战第25天】异步编程对于提升软件应用的性能至关重要,尤其是在高并发环境下。Spring Boot 通过 `@Async` 注解简化了异步方法的实现。本文详细介绍了 `@Async` 的基本用法及配置步骤,并提供了示例代码展示如何在 Spring Boot 项目中创建与管理异步任务,包括自定义线程池、使用 `CompletableFuture` 处理结果及异常情况,帮助开发者更好地理解和运用这一关键特性。
125 1
|
2月前
|
资源调度 Java 调度
Spring Cloud Alibaba 集成分布式定时任务调度功能
定时任务在企业应用中至关重要,常用于异步数据处理、自动化运维等场景。在单体应用中,利用Java的`java.util.Timer`或Spring的`@Scheduled`即可轻松实现。然而,进入微服务架构后,任务可能因多节点并发执行而重复。Spring Cloud Alibaba为此发布了Scheduling模块,提供轻量级、高可用的分布式定时任务解决方案,支持防重复执行、分片运行等功能,并可通过`spring-cloud-starter-alibaba-schedulerx`快速集成。用户可选择基于阿里云SchedulerX托管服务或采用本地开源方案(如ShedLock)
|
28天前
|
存储 安全 Java
SpringBoot异步任务获取HttpServletRequest
通过上述方法,我们可以在Spring Boot应用中的异步任务获取 `HttpServletRequest`,从而实现更为灵活和高效的异步处理逻辑。
179 64
|
7天前
|
Java Spring 容器
Spring使用异步注解@Async正确姿势
Spring使用异步注解@Async正确姿势,异步任务,spring boot
消息中间件 缓存 监控
81 0
|
3月前
|
资源调度 Java 调度
Spring Cloud Alibaba 集成分布式定时任务调度功能
Spring Cloud Alibaba 发布了 Scheduling 任务调度模块 [#3732]提供了一套开源、轻量级、高可用的定时任务解决方案,帮助您快速开发微服务体系下的分布式定时任务。
14657 24
|
2月前
|
监控 Java API
Spring Boot中的异步革命:构建高性能的现代Web应用
【8月更文挑战第29天】Spring Boot 是一个简化 Spring 应用开发与部署的框架。异步任务处理通过后台线程执行耗时操作,提升用户体验和系统并发能力。要在 Spring Boot 中启用异步任务,需在配置类上添加 `@EnableAsync` 注解,并定义一个自定义的 `ThreadPoolTaskExecutor` 或使用默认线程池。通过 `@Async` 注解的方法将在异步线程中执行。异步任务适用于发送电子邮件、数据处理、外部 API 调用和定时任务等场景。最佳实践中应注意正确配置线程池、处理返回值和异常、以及监控任务状态,确保系统的稳定性和健壮性。
31 0
|
2月前
|
Java 开发者 Spring
Spring Boot实战宝典:揭秘定时任务的幕后英雄,让业务处理如流水般顺畅,轻松驾驭时间管理艺术!
【8月更文挑战第29天】在现代应用开发中,定时任务如数据备份、报告生成等至关重要。Spring Boot作为流行的Java框架,凭借其强大的集成能力和简洁的配置方式,为开发者提供了高效的定时任务解决方案。本文详细介绍了如何在Spring Boot项目中启用定时任务支持、编写定时任务方法,并通过实战案例展示了其在业务场景中的应用,同时提供了注意事项以确保任务的正确执行。
36 0
|
2月前
|
Java 开发者 Spring
Spring Boot大法好:解耦、隔离、异步,让代码‘活’起来,性能飙升的秘密武器!
【8月更文挑战第29天】解耦、隔离与异步是Spring Boot中的关键设计原则,能大幅提升软件的可维护性、扩展性和性能。本文通过示例代码详细探讨了这些原则的应用:依赖注入和面向接口编程实现解耦;模块化设计与配置文件实现隔离;`@Async`注解和`CompletableFuture`实现异步处理。综合运用这些原则,可以显著提升软件质量和性能,使系统更加健壮、灵活和高效。
22 0
|
3月前
|
Java Spring 容器
Spring boot 自定义ThreadPoolTaskExecutor 线程池并进行异步操作
Spring boot 自定义ThreadPoolTaskExecutor 线程池并进行异步操作
75 3
下一篇
无影云桌面