- 一、异步任务
- 二、定时任务
- 1、cron表达式
- 2、测试
- 三、邮件任务
在Java应用中,绝大多数情况下都是通过同步
的方式来实现交互处理的;但是在处理与第三方系统交互的时候,容易造成响应迟缓的情况,之前大部分都是使用多线程
来完成此类任务,其实,在Spring 3.x之后,就已经内置了@Async
来完美解决这个问题。
两个注解: @EnableAysnc
、@Aysnc
@RestController
public class AsyncController {
@Resource
private AsyncService asyncService;
@GetMapping("/hello")
public String hello(){
asyncService.hello();
return "success";
}
}
要开启异步任务注解的功能,使用 @EnableAsync
@EnableAsync // 开启异步注解功能
@SpringBootApplication
public class Springboot05TastApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot05TastApplication.class, args);
}
}
@Service
public class AsyncService {
@Async // 表示这是一个异步方法,再线程池中获取一个线程来单独执行该方法
public void hello() {
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("处理数据中..");
}
}
二、定时任务
跳转到目录 项目开发中经常需要执行一些定时任务,比如需要在每天凌晨时候,分析一次前一天的日志信息。Spring为我们提供了异步执行任务调度的方式,提供TaskExecutor
、TaskScheduler
接口。
两个注解: @EnableScheduling
、@Scheduled
second(秒) minute(分) hour(时) day of month(日) month(月) day of week(周几) 下面的符号对应上面六个 0 * * * * MON-FRI 表示周五到周一之间,每月的周一到周五每时每分每0秒的时候会执行任务
例子: 【0 0/5 14,18 * * ?】 每天14点整,和18点整,每隔5分钟执行一次 【0 15 10 ? * 1-6】 每个月的周一至周六10:15分执行一次 【0 0 2 ? * 6L】每个月的最后一个周六凌晨2点执行一次 【0 0 2 LW * ?】每个月的最后一个工作日凌晨2点执行一次 【0 0 2-4 ? * 1#1】每个月的第一个周一凌晨2点到4点期间,每个整点都执行一次;
2、测试@EnableScheduling
: 开启基于注解的定时任务功能
@EnableScheduling // 开启基于注解的定时任务功能
@SpringBootApplication
public class Springboot05TastApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot05TastApplication.class, args);
}
}
@Service
public class ScheduledService {
//定时注解中需要传入 cron表达式
//@Scheduled(cron = "0 * * * * MON-FRI")
//@Scheduled(cron = "1,2,3,4,5 * * * * MON-FRI") // 第1,2,3,4,5秒执行(范围:周一到周五,每分钟的前五秒)
//@Scheduled(cron = "1-5 * * * * MON-FRI") // 同上
@Scheduled(cron = "0/10 * * * * MON-SAT") // 每4秒执行一次
public void hello(){
System.out.println("hello..");
}
}
跳转到目录 使用步骤:
- 邮件发送需要引入spring-boot-starter-mail
- Spring Boot 自动配置
MailSenderAutoConfiguration
- 定义MailProperties内容,配置在application.properties中
- 自动装配JavaMailSender
- 测试邮件发送
- 在全局配置文件application.properties中配置
其中
spring.mail.password=xxx
是在QQ邮箱的设置->账户中生成的授权码
; - 测试邮件发送
@SpringBootTest
class Springboot05TastApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
void contextLoads() {
// 创建一个简单的邮箱信息对象
SimpleMailMessage message = new SimpleMailMessage();
// 邮件设置
message.setSubject("通知-今晚开会"); //标题
message.setText("今晚7:30开会!"); //邮件内容
message.setTo("Xxxx@163.com"); //发给谁
message.setFrom("Xxxx@qq.com"); //谁发的
mailSender.send(message);
}
@Test
void test2() throws Exception{
// 创建一个复杂的消息邮件(可以有样式、附件等内容)
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
// 邮件设置
helper.setSubject("通知-今晚开会"); //标题
helper.setText("今晚7:30开会!", true); //邮件内容
helper.setTo("Xxxx@163.com"); //发给谁
helper.setFrom("Xxxx@qq.com"); //谁发的
// 上传文件
helper.addAttachment("1.jpg", new File("/Users/qw/Desktop/1.jpg"));
mailSender.send(mimeMessage);
}
}