这里是 学习链接
在SpringBoot的使用
肯定是先创建一个工程,导入依赖只导入Spring Web 依赖即可
1.异步任务
(1)在方法中添加注释 @Async
@Service
public class AsyncService {
/**
* 模拟服务 睡眠三秒
*/
@Async
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("你运行了hello()方法");
}
}
(2)启动类加上开启异步功能注解
@SpringBootApplication
@EnableAsync
public class MyemailsApplication {
public static void main(String[] args) {
SpringApplication.run(MyemailsApplication.class, args);
}
}
2.邮件任务
(1)导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
(2)配制邮箱基本信息
spring.mail.username=qq号@qq.com
spring.mail.password=wipmhjkascribfih(自动生成的密码)
spring.mail.host=smtp.qq.com
# 开启加密验证规则
spring.mail.properties.mail.stmp.ssl.enable=true
(3)单元测试邮件的发送
- 简单邮件
/**
* 发送简单邮件
*/
@Test
void contextLoads(){
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("老白的测试邮件");//主题
message.setText("文本内容");//文本内容
message.setTo("1005777@qq.com");//发送给
message.setFrom("1005777@qq.com");//来自哪
sender.send(message);
}
- 复杂邮件
/**
* 发送复杂邮件
*/
@Test
void contextLoadss() throws MessagingException {
MimeMessage message = sender.createMimeMessage();
//组装邮件
MimeMessageHelper helper = new MimeMessageHelper(message,true);
helper.setSubject("老白的测试邮件+++");//主题
helper.setText("<h1>文本内容</h1>",true);//文本内容
//附件
helper.addAttachment("tupian.jpg",new File("C:\\Users\\老白\\Desktop\\QQ截图20200808192435.jpg"));
helper.setTo("1005777@qq.com");//发送给
helper.setFrom("1005777@qq.com");//来自哪
sender.send(message);
}
3.定时任务
TaskScheduler 任务调度者
TaskExecutor 任务执行者
@EnableScheduling 开启定时功能注解
@Scheduled 什么时候执行
Cron 表达式
@SpringBootApplication
@EnableAsync
@EnableScheduling
public class MyemailsApplication {
public static void main(String[] args) {
SpringApplication.run(MyemailsApplication.class, args);
}
}
@Service
public class ScheduledService {
/**
* 在特定时间执行这个方法
* cron() 计划任务,表达式
*/
/**
* <p>
* crontab文件的格式:M H D m d
* M: 分钟(0-59)。
* H:小时(0-23)。
* D:天(1-31)。
* m: 月(1-12)。
* d: 一星期内的天(0~7,0和7均为星期天)。
* </p>
* <p>
* 分钟 (0-59)
* 小时 (0-23)
* 日期 (1-31)
* 月份 (1-12)
* 星期 (0-7)// 0和7均代表星期天
* </p>
* <p>
* cron = "0 * * * * 0-7"
* 秒 分 时 日 月 周几
* </p>
* <p>
* *代表所有的取值范围内的数字
* "-"代表从某个数字到某个数字
* "/"代表每的意思
* ","分开几个离散的数字
* </p>
*/
@Scheduled(cron = "0 44 19 * * 0-7")
public void hello(){
System.out.println("你被执行了");
}
}