- 异步任务
- 定时任务
- 邮件发送(常用,springboot官方)
一、异步任务
1、创建一个springboot项目,勾选web启动器依赖
2、新建一个业务
但是数据处理会线程休眠3秒,休眠期间页面会无显示
@Service//由spring托管的业务
public class AsyncService {
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在处理...");
}
}
3、编写controller调用这个业务
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@RequestMapping("/hello")
public String hello(){
asyncService.hello();//停止三秒,转圈
return "ok";
}
}
4、转换成异步任务
在业务代码块中加上@Async异步任务注解
然后在主程序开启异步功能注解
那么就可以先执行返回结果ok,中间的线程休眠(也就是数据处理在后台运行三秒,然后展现出来)
二、邮件任务
1、添加邮件springboot启动器
<!--启动邮件功能-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2、发送一个简单的邮件,以及测试效果
3、发送复杂的邮件,及其测试效果
下面的代码在业务中放在controller层
4、将邮件发送封装成一个工具类
还自带注释
/**
*
* @param html
* @param subject
* @param text
* @throws MessagingException
* @Autor 晴空
*/
//发送邮件工具类
public void sendMail(Boolean html,String subject,String text) throws MessagingException {
//一个复杂的邮件
MimeMessage mimeMessage = mailSender.createMimeMessage();
//组装
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
//正文
helper.setSubject(subject);//主题
helper.setText(text,html);//第二个参数可以开启支持html解析
//附件
helper.addAttachment("1.jpg",new File("D:\\桌面\\1.jpg"));
helper.addAttachment("2.jpg",new File("D:\\桌面\\1.jpg"));
helper.setTo("869729243@qq.com");//收件人
helper.setFrom("869729243@qq.com");//发件人
mailSender.send(mimeMessage);
}
三、定时任务
两个核心接口
TaskExecutor 任务执行者
TaskScheduler 任务调度器——具有定时的功能
@EnableScheduling 开启定时功能的注解
@Scheduled 什么时候执行
Cron表达式
1、编写需要定时执行的业务代码
记得这任务要想被springboot主程序执行,需要加上@Service注解
@Scheduled(cron = "0 32 15 * * ?")定时执行时间注解
(cron表达式解释:每月每日每周几的15时32分0秒执行这个任务)
注意:
- cron表达式的?占位符和*占位符区别:?表示不指定准确时间,*表示所有都时间都执行,星期和月的日容易冲突,所以要用?站位
- 参数格式cron = “秒 分 时 日 月 周”
@Service
public class ScheduleService {
//在一个特定的时间执行这个方法
//cron表达式
// 秒 分 时 日 月 周
@Scheduled(cron = "0 32 15 * * ?")
public void hello(){
System.out.println("hello被执行了");
}
}
2、在主程序类开启定时任务执行
@EnableScheduling//开启定时功能的注解