8. 异步任务
(1) 开启异步注解
@EnableAsync
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
(2) 声明异步方法
@Service
public class AsyncService {
@Async
public void sleep() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在处理...");
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
Date edate = new Date(System.currentTimeMillis());
System.out.println("edate:" + formater.format(edate));
}
}
(3) 调用异步方法
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@RequestMapping("/sleep")
public String sleep() {
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
Date sdate = new Date(System.currentTimeMillis());
System.out.println("sdate:" + formater.format(sdate));
asyncService.sleep();
return "OK";
}
}
(4) 测试效果


9. 邮件发送
(1) 配置
spring.mail.username=1942953841@qq.com
spring.mail.password=wedahkcfqhwkfdcg
spring.mail.host=smtp.qq.com
spring.mail.properties.mail.smtp.ssl.enable=true
(2) 测试
@Autowired
JavaMailSenderImpl mailSender;
@Test
void sendSimpleMail() {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setSubject("Hello");
mailMessage.setText("Nice to meet you !");
mailMessage.setTo("486530039@qq.com");
mailMessage.setFrom("1942953841@qq.com");
mailSender.send(mailMessage);
}
@Test
void sendMimeMail() throws MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setSubject("Hello");
helper.setText("<p style='color:blue'>Nice to meet you !</p>", true);
helper.addAttachment("鬼泣DMC.jpg", new File("C:\\Users\\LENOVO\\Pictures\\鬼泣DMC.jpg"));
helper.setTo("486530039@qq.com");
helper.setFrom("1942953841@qq.com");
mailSender.send(mimeMessage);
}
10. 定时执行
(1) 启动定时注解
@EnableScheduling
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
(2) 测试
@Service
public class ScheduledService {
@Scheduled(cron = "30 * * * * 0-7")
public void timer30() {
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
Date date = new Date(System.currentTimeMillis());
System.out.println("Time is " + formater.format(date));
}
}
