// 启动类
@EnableAsync
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
// service
@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));
}
}
// controller
@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";
}
}
# application.properties
spring.mail.username=1942953841@qq.com
spring.mail.password=wedahkcfqhwkfdcg
spring.mail.host=smtp.qq.com
# qq 邮箱开启加密验证
spring.mail.properties.mail.smtp.ssl.enable=true
@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("Nice to meet you !
", 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);
}
// 启动类
@EnableScheduling // 开启定时功能
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
@Service
public class ScheduledService {
// corn 表达式
// 秒 分 时 日 月 星期
@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));
}
}