Springboot异步、邮件发送、定时任务

本文介绍了如何在SpringBoot中实现异步任务,详细讲解了开启异步注解、编写异步服务及控制器的步骤。接着讨论了邮件发送,包括添加依赖、配置和测试方法。最后探讨了SpringBoot定时任务的多种实现方式,如Timer、ScheduledExecutorService、Spring Task和Quartz,并展示了如何使用@Scheduled注解进行定时任务设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

准备工具:IntelliJ IDEA

Springboot异步任务:
1.SpringbootApplication 开启异步注解功能 @EnableAsync

@EnableAsync // 开启异步注解功能
@SpringBootApplication
public class SpringbootApplication {
    public static void main(String[] args) {
        SpringApplication.run(Springboot09TestApplication.class, args);
    }
}
  1. 编写AsyncService类 添加进 @Service ,方法上添加 @Async 告诉spring这是一个异步方法

注意:在类上添加@Async表示这个类下的所有方法都是异步
方法上添加@Async表示这个方法都异步
@Async所修饰的函数不要定义为static类型,这样异步调用不会生效。
本类的方法添加@Async,在本类中调用并不会异步,因为注解异步@Async是通过代理类来调用的。
若在类中直接调用,相当于this.xxx的方式,即是通过MyJobService对象直接调用的xxx方法

@Service
public class AsyncService {
    @Async //告诉spring这是一个异步方法
    public void helo(){
        //快捷键  ctrl+alt+t
        try {
            Thread.sleep(3000);//等待3秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("数据正在加载......");
    }
}
  1. AsyncController 控制器 ,注入 AsyncService 写方法调用 .helo()
@RestController
public class AsyncController {
    @Autowired
    AsyncService asyncService;
    // 异步测试  
    @RequestMapping("/hello")
    public String hello(){
        asyncService.helo();//停3秒
        return "OK";
    }
}

4.运行时并没有直接就返回OK,而是在三秒后才返回,期间可以看到刷新按钮一直是加载的状态,由此可以看出该异步是做到了,所有任务执行完成才返回,任务执行时间正常,主线程等待其他线程完成后结束。
在这里插入图片描述

异步了解了也可以看看同步的效果
首先引依赖

   <!--  lombok.extern.slf4j.Slf4j;  -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

创建任务服务类(未做异步处理)、加入容器

package com.hh.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Component
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值