SpringBoot 异步、邮件、定时任务
异步任务
Springboot09EmailApplication.java
@EnableAsync//开启异步注解功能
@SpringBootApplication
public class Springboot09EmailApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot09EmailApplication.class, args);
}
}
AsyncService.java
@Service
public class AsyncService {
//告诉spring 这是一个异步的方法
@Async
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("三秒已走完");
}
}
邮件发送
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
application.properties
spring.mail.username=123456789@qq.com
spring.mail.password=agdfsyfvdfdvbcfs
spring.mail.host=smtp.qq.com
#开启加密验证
spring.mail.properties.smtl.ssl.enable=true
Springboot09EmailApplicationTests.java
@SpringBootTest
class Springboot09EmailApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
void contextLoads() {
//一个简单的邮件
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setSubject("小狂神你好呀~");
simpleMailMessage.setText("谢谢你的狂神说JAVA系列~");
simpleMailMessage.setTo("fasondao@qq.com");
simpleMailMessage.setFrom("beifason@qq.com");
mailSender.send(simpleMailMessage);
}
@Test
void contextLoads2() throws MessagingException {
//一个简单的邮件
MimeMessage mimeMessage = mailSender.createMimeMessage();
//组装
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
//正文
helper.setSubject("小狂神你好呀~plus");
helper.setText("<p style='color:red'>谢谢你的狂神说JAVA系列~</p>",true);
//附件
helper.addAttachment("1.jpg",new File("D:\\图片\\1.jpg"));
helper.addAttachment("2.jpg",new File("D:\\图片\\2.gif"));
helper.setTo("fasondao@qq.com");
helper.setFrom("beifason@qq.com");
mailSender.send(mimeMessage);
}
}
任务调度
Springboot09EmailApplication.java
@EnableScheduling//开启定时功能的注解
@SpringBootApplication
public class Springboot09EmailApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot09EmailApplication.class, args);
}
}
ScheduleService.java
@Service
public class ScheduleService {
//在一个特点的时间执行这个方法
//cron表达式
//秒 分 时 日 月 周几
@Scheduled(cron = "0/10 * * * * ?")
public void hello(){
System.out.println("hello,你被执行了~");
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)