java 异步定时任务_spring 定时任务 & 异步调用

本文介绍了如何在 SpringBoot 中实现定时任务和异步调用。通过 @Scheduled 和 @Async 注解,配合 Cron 表达式,轻松设置定时任务和异步方法。同时讲解了如何自定义线程池、获取异步调用结果、异常处理以及使用 @EnableAsync 和 AsyncConfigurerSupport 进行全局配置。
摘要由CSDN通过智能技术生成

本篇仅限于 Spring 定时任务 & 异步调用的基本使用,不涉及深入原理探究,先学会怎么用,再探究原理.

环境:SpringBoot 2.0

定时任务指的是应用程序在指定的时间执行预先定义好的程序片段

在 Spring 中使用定时任务非常简便,分为三步:编写定时任务类并注入到 IOC 容器,一般使用 @Component 注入

编写定时任务方法并使用 @Scheduled 标记,这里需要了解一个叫 Cron 表达式的知识点

在 SpringBoot 启动类上使用 @EnableScheduling 开启定时任务功能

/*** 1、注入到 IOC 容器,定时任务不属于 service 或 controller,一般使用 @Component 标注*/

@Slf4j

@Component

public class HelloScheduled {

/*** 2、编写定时任务方法并使用 @Scheduled 标记* 注意:@Scheduled cron 属性中书写的是 cron 表达式,如下的 cron 表达式表示:每隔5秒执行一次*/

@Scheduled(cron = "*/5 * * * * ?")

public void scheduled() {

log.info("使用 Spring @Scheduled 制定定时任务");

}

}

/*** 3、在 `SpringBoot` 启动类上使用 `@EnableScheduling` 开启定时任务*/

@EnableScheduling

@SpringBootApplication

public class SpringAllApplication {

public static void main(String[] args) {

SpringApplication.run(SpringAllApplication.class, args);

}

}

自定义配置文件

上述代码我们是在SpringBoot启动类上使用@EnableScheduling开启定时任务,而在实际开发我们会使用JavaConfig配置并约束package,使得指定的组件只有在指定package才有效.

/*** 定时任务只扫描 HelloScheduled 类所在的包*/

@EnableScheduling

@Configuration

@ComponentScan(basePackageClasses = com.xbhel.springall

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值