任务
- 异步任务
- 定时任务
- 邮件发送
一、异步任务
在执行多线程的方法打上@Async注解
@Service
public class AsyncService {
@Async//告诉spring这是一个异步任务
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在处理。。。");
}
}
@RestController
public class HelloController {
@Autowired
private AsyncService service;
@GetMapping("/hello")
public String hello() {
service.hello();
return "OK";
}
}
@SpringBootApplication
@EnableAsync//开启多线任务
public class TaskDemoApplication {
public static void main(String[] args) {
SpringApplication.run(TaskDemoApplication.class, args);
}
}
这样的话,前端页面就不会产生等待时间,会直接刷新数据,数据正在打印。。。会在后台执行,等待三秒后输出。
二、邮件发送
- 导入jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
在qq邮箱中开启服务(设置–> 账户),验证后会得到一个授权码,添加到下面的配置中。

添加主要配置
spring.mail.username=填你的邮箱
spring.mail.password=授权码
spring.mail.host=smtp.qq.com
#开启加密验证(qq邮箱需要,其他不需要)
spring.mail.properties.mail.smtp.ssl.enable=true
测试发送
@Autowired
JavaMailSenderImpl mailSender;
@Test
void contextLoads() {
//发送一个简单邮件
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("我爱你");
message.setText("我亲爱的小葱,我是你的大胖子!!!");
message.setTo("13994897625@163.com");
// message.setTo("1191599851@qq.com");
message.setFrom("1191599851@qq.com");
mailSender.send(message);
}
@Autowired
JavaMailSenderImpl mailSender;
@Test
void contextLoads2() throws MessagingException {
//复杂邮件发送
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
//设置文本内容
helper.setSubject("我爱你");
//true表示能够解析html文本
helper.setText("<p style='color:red;'>我亲爱的小葱,我是你的大胖子!!!</p>",true);
//添加附件
helper.addAttachment("头像",new File("/home/zhaoli/Desktop/1.jpeg"));
helper.addAttachment("头像2",new File("/home/zhaoli/Desktop/1.jpeg"));
//设置接受人和发送人
helper.setTo("1191599851@qq.com");
helper.setFrom("1191599851@qq.com");
mailSender.send(mimeMessage);
}
三、定时任务
TaskScheduler 任务调度程序
TaskExecutor 任务执行者
@EnableScheduling //开启定时功能的注解
@Scheduled //什么时候执行
Cron表达式
秒 分 时 日 月 周几
@Scheduled(cron = "0/2 * * * * ?")
Cron表达式范例:
每隔5秒执行一次:*/5 * * * * ?
每隔1分钟执行一次:0 */1 * * * ?
每天23点执行一次:0 0 23 * * ?
每天凌晨1点执行一次:0 0 1 * * ?
每月1号凌晨1点执行一次:0 0 1 1 * ?
每月最后一天23点执行一次:0 0 23 L * ?
每周星期天凌晨1点实行一次:0 0 1 ? * L
在26分、29分、33分执行一次:0 26,29,33 * * * ?
每天的0点、13点、18点、21点都执行一次:0 0 0,13,18,21 * * ?
@SpringBootApplication
@EnableScheduling //开启任务调度程序的注解
public class TaskDemoApplication {
public static void main(String[] args) {
SpringApplication.run(TaskDemoApplication.class, args);
}
}
@Service
public class ScheduledService {
//表示该方法每隔两秒执行一次
@Scheduled(cron = "0/2 * * * * ?")
public void hello(){
System.out.println("hello,你被执行了");
}
}
本文介绍如何在Spring Boot中实现异步任务处理和定时邮件发送功能,包括使用@Async注解创建异步任务,配置邮件服务并发送邮件,以及通过Cron表达式设置定时任务。
399

被折叠的 条评论
为什么被折叠?



