异步任务、邮件任务、定时任务

本文详细介绍如何在Spring Boot中实现异步任务处理,包括邮件发送功能的配置与使用,以及定时任务的设置与Cron表达式的应用。通过具体代码示例,读者可以了解如何创建并发送简单及复杂的邮件,同时掌握如何利用TaskScheduler和TaskExecutor执行定时任务。

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

异步任务

  • @Async //在需要进行异步的方法上加注解
  • @EnableAsync //在启动类上开启异步注解的功能

邮件任务

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

配置文件

spring.mail.username=自己的邮箱
spring.mail.password=邮箱的SMTP码
spring.mail.host=smtp.qq.com
#开启加密认证
spring.mail.properties.mail.smtp.ssl.enable=true
  • 使用邮件发送
package com.hzy;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@SpringBootTest
class Springboot08TestApplicationTests {
    @Autowired
    JavaMailSenderImpl javaMailSender;
    @Test
    void contextLoads() {
//        一个简单的邮件
        SimpleMailMessage mailMessage=new SimpleMailMessage();
        mailMessage.setSubject("标题:你好啊!");
        mailMessage.setText("内容!!!哈哈隔!");
        mailMessage.setTo("发送人邮箱");
        mailMessage.setFrom("接收人邮箱");
        javaMailSender.send(mailMessage);
    }
    @Test
    void contextLoadss() throws MessagingException {
//        一个复杂的邮件
        MimeMessage mimeMessage=javaMailSender.createMimeMessage();
//        组装
        MimeMessageHelper helper=new MimeMessageHelper(mimeMessage,true);
        helper.setSubject("标题");
        helper.setText("<h1 style='color:red;'>内容!!!哈哈隔!</h1>",true);//加上true解析html
        helper.addAttachment("附件名1.jpg",new File("绝对路径/相对路径"));//附件
        helper.addAttachment("附件名2.jpg",new File("绝对路径/相对路径"));
        helper.setTo("发送人邮箱");
        helper.setFrom("接收人邮箱");
        javaMailSender.send(mimeMessage);
    }
}

定时任务

  • TaskScheduler 任务调度者
  • TaskExecutor 任务执行者
  • @EnableScheduling //在启动类上开启定时任务的注解
  • @Scheduled //什么时候执行
  • Cron表达式

@EnableScheduling //在启动类上开启定时任务的注解

//    在一个特定的时间执行这个方法~Timer
//    cron表达式     秒 分 时 日 月 周几
//    例  30 15 10 * * ? 每天的10点15分30执行一次
    @Scheduled(cron="0 * * * * ?")
    public void hello(){
        System.out.println("Hello,你被执行了~");
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值