异步任务
- @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,你被执行了~");
}