异步任务
异步任务:
添加异步任务,即开启多线程只需要在方法上添加注解@Async //@Async 告诉Spring是一个异步任务
然后在Main方法上开启此功能即可。
//开启异步任务
@EnableAsync
@SpringBootApplication
public class SpringbootestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootestApplication.class, args);
}
}
定时任务
//开启定时任务的支持
@EnableScheduling
//什么时候执行
@Scheduled
首先在Main放上配置注解@EnableScheduling 开启服务的支持
//开启定时任务的支持
@EnableScheduling
@SpringBootApplication
public class SpringbootestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootestApplication.class, args);
}
}
在方法上添加@Scheduled方法规定执行时间
// 秒 分 时 日 月 周几 6个参数
@Scheduled(cron = "0 09 13 * * 0-7")
public void Hello()
{
System.out.println("Hello");
}
CRON表达式例子
每隔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 * * ?
邮件发送
Springboot中使用邮件只需添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
邮件的配置
spring.mail.username=邮箱账户
spring.mail.password=客户端授权码,邮箱给定的不是密码
spring.mail.host=smtp.qq.com 设置邮件服务器(不同邮箱不同这里是qq)
#上面三个是必须配置的
spring.mail.port=465 发送的端口
spring.mail.default-encoding=utf-8 编码方式
#开启加密验证 qq邮箱才需要配置
spring.mail.properties.mail.smtp.ssl.enable=true
授权码通过开启POP3/SMTP服务得到,在邮箱设置–账户中可以找到。
邮件发送的实现通过类JavaMailSenderImpl来实现
//JavaMailSenderImpl 邮件发送实现类
@Autowired
JavaMailSenderImpl MailSender;
//简单邮件的实现
@Test
void contextLoad()
{
//配置发送邮件信息
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setSubject("发送的标题");
mailMessage.setText("发送的内容");
//收件人地址
mailMessage.setTo("xxxxxxx@qq.com");
//发件人邮箱,注意applicationContext中的邮箱一致,否则报501错误
mailMessage.setFrom("xxxxxxx@qq.com");
MailSender.send(mailMessage);
}
//复杂邮件的实现
@Test
void contextLoad2() throws MessagingException {
//配置发送邮件信息
MimeMessage message = MailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(message,"UTF-8");
messageHelper.setSubject("主题");
messageHelper.setText("<p style='color:red'>内容</p>");
//附件
messageHelper.addAttachment("文件名字",new File("文件地址"));
messageHelper.setTo("xxxxxxx@qq.com");//收件人地址
messageHelper.setFrom("xxxxxx@qq.com");//发件人邮箱
MailSender.send(message);
}