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

62 篇文章 3 订阅

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

异步任务

在springboot启动类上增加@EnableAsync // 开启异步注解功能

在要调用的异步方法上增加@Async注解

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Zw1TyTNB-1662639933309)(/Users/cat/Library/Application Support/typora-user-images/image-20220908191920110.png)]

直接调用即可,完成异步处理任务

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5LEUudf0-1662639933309)(/Users/cat/Library/Application Support/typora-user-images/image-20220908192132484.png)]

邮件任务

引入依赖

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

以QQ邮箱为例,qq邮箱为了保护密码隐私需要开启POP3/SMTP服务,获取授权码,其他的可能不用

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EjQcvuCJ-1662639933310)(/Users/cat/Library/Application Support/typora-user-images/image-20220908193039493.png)]

配置

spring:
  mail:
    username: xxx@qq.com
    password: 授权码
    host: smtp.qq.com
    properties:
      mail:
        smtp:
          ssl:
            enable: true

测试

@Autowired
private JavaMailSenderImpl mailSender;

/**
 * 邮件任务测试
 */
@Test
void sendMailTest() {
  //一个简单邮件
  SimpleMailMessage message = new SimpleMailMessage();
  message.setSubject("邮件主题");
  message.setText("内容~谢谢");
  message.setTo("hexuan.cat@gmail.com");
  message.setFrom("2272062968@qq.com");
  mailSender.send(message);
}

/**
 * 复杂邮件
 */
@Test
void sendMailComplexTest() throws MessagingException {
  //一个复杂邮件
  MimeMessage mimeMessage = mailSender.createMimeMessage();
  //组装
  MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
  helper.setSubject("主题");
  helper.setText("<p style='color:red'>hello world</p>", true);
  //附件
  helper.addAttachment("1.jpg", new File("/Users/cat/Documents/1.png"));
  helper.addAttachment("2.jpg", new File("/Users/cat/Documents/1.png"));

  helper.setTo("hexuan.cat@gmail.com");
  helper.setFrom("2272062968@qq.com");
  mailSender.send(mimeMessage);
}

运行测试用例,即可收到发送的邮件啦
请添加图片描述

定时任务

在SpringBoot启动类上增加@EnableScheduling // 开启定时任务注解

Service定时任务,使用cron表达式实现

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class ScheduledService {
    //cros表达式 秒 分 时 日 月 周几
    @Scheduled(cron = "*/5 * * * * ?")  //每5秒执行一次
    public void hello() {
        System.out.println("hello,执行成功");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

摘星喵Pro

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值