异步任务
- 在启动类上开启异步注解功能 @EnableAsync
@EnableAsync //开启异步注解功能
@SpringBootApplication
public class Springboot09TestApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot09TestApplication.class, args);
}
}
- 将一个任务加上@Async,就标明这个任务是一个异步任务,调用时,会取线程池,单独开一条线程取执行。
@Service
public class AsyncService {
@Async //告诉spring这是一个异步方法
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("任务正在处理中");
}
}
定时任务
springboot自带定时功能
TaskScheduler 任务调度程序
TaskExecutor 任务执行程序
@EnableScheduling//开启定时注解功能,加到启动类
@Scheduled(cron = " * * * * * * ") //任务什么时候执行,加到执行的方法上
cron表达式 详见
邮件任务
- 导包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
- yml中配置发送邮件的属性
spring:
mail:
username: 592844440@qq.com
password: bocujsjfolqnbfia
host: smtp.qq.com
#开启加密验证
properties.mail.smtp.ssl.enable: true
- 编写发送邮件代码
简单的文本邮件
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("我是邮件标题");
message.setText("我爱死你了");
message.setTo("592844440@qq.com");
message.setFrom("592844440@qq.com");
sender.send(message);
复杂的多文本邮件
//一个复杂的邮件
MimeMessage mimeMessage = sender.createMimeMessage();
//true 为支持多文本上传
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
//上传附件
helper.addAttachment("1.jpg",new File("C:\\Users\\Administrator\\Desktop\\摄影原理.png"));
helper.addAttachment("2.jpg",new File("C:\\Users\\Administrator\\Desktop\\摄影原理.png"));
//编写主题和内容
helper.setSubject("我爱死你了");
//text 设置为true,则可以将内容以html格式输出
helper.setText("<div style=color:red>我想和你看日落</div>",true);
helper.setTo("592844440@qq.com");
helper.setFrom("592844440@qq.com");
//发送
sender.send(mimeMessage);