SpringBoot与任务
一、异步任务:
-
开启异步注解:
@EnableAsync //开启异步注解功能
-
使用@Async,诉Spring这是一个异步方法
@Async public void hello(){ try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("处理数据中..."); } //直接输入,程序不会顺序执行
二、定时任务:
-
开启基于注解的定时任务
@EnableScheduling //开启基于注解的定时任务
-
使用@Scheduled来规定什么时间执行:
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; @Service public class ScheduledService { /** * second(秒), minute(分), hour(时), day of month(日), month(月), day of week(周几). * 0 * * * * MON-FRI周一到周五 * 【0 0/5 14,18 * * ?】 每天14点整,和18点整,每隔5分钟执行一次 * 【0 15 10 ? * 1-6】 每个月的周一至周六10:15分执行一次 * 【0 0 2 ? * 6L】每个月的最后一个周六凌晨2点执行一次 * 【0 0 2 LW * ?】每个月的最后一个工作日凌晨2点执行一次 * 【0 0 2-4 ? * 1#1】每个月的第一个周一凌晨2点到4点期间,每个整点都执行一次; */ @Scheduled(cron = "0/4 * * * * MON-SAT") // public void hello(){ System.out.println("hello ... "); } }
-
cron表达式规则:
三、邮件任务:
-
添加依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
-
配置资源文件:(发送者的信息)
spring.mail.username=********@qq.com spring.mail.password=******* spring.mail.host=smtp.qq.com spring.mail.properties.mail.smtp.ssl.enable=true
.password不是邮箱的登录密码,而是一个授权码。QQ邮箱的授权码可在 设置—账户—开启服务下进行生成,如下图所示:
-
测试:(简单的邮件)
@Test public void contextLoads() { SimpleMailMessage message = new SimpleMailMessage(); //邮件设置 message.setSubject("通知-今晚开会"); message.setText("今晚7:30开会"); message.setTo("15911613834@163.com");//可设置多个 message.setFrom("940404240@qq.com"); mailSender.send(message); }
-
测试发送复杂的邮件
@Test public void test02() throws Exception{ //1、创建一个复杂的消息邮件 MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); //邮件设置 helper.setSubject("通知-今晚开会"); helper.setText("<b style='color:red'>今天 7:30 开会</b>",true); helper.setTo("17512080612@163.com"); helper.setFrom("534096094@qq.com"); //上传文件 helper.addAttachment("1.jpg",new File("C:\\Users\\lfy\\Pictures\\Saved Pictures\\1.jpg")); helper.addAttachment("2.jpg",new File("C:\\Users\\lfy\\Pictures\\Saved Pictures\\2.jpg")); mailSender.send(mimeMessage); }