SpringBoot学习系列(十七)------SpringBoot与任务
前言
任务调度在我们的项目开发中是使用比较频繁的技术,SpringBoot中怎么实现任务调度呢?在这里我们一起来学习一下.
正文
1. SpringBoot实现异步任务
异步任务一般是通过多线程的方式来实现的,在Spring3以后,就内置了对异步任务的支持,我们可以使用注解@Async来简化我们的开发
- 在需要异步处理的方法上添加注解
@Async
即可让Spring自动创建线程处理该任务 - 在启动类上添加注解
@EnableAsync
来开启SpringBoot对异步任务的支持
现在我们访问该方法,即可异步执行.这里就不贴代码.
2. SpringBoot实现定时任务
在SpringBoot中实现定时任务也很方便我们只需要使用两个注解@EnableScheduling
和@Scheduled
@Enablescheduling
写在启动类上代表开启定时任务支持
@Scheduled
写在方法上,代表具体执行的方法
在@Scheduled
注解中,我们可以使用属性cron
来指定一个cron表达式具体我们执行任务的时间,关于cron表达式,可以查看一下图中的标识:
具体使用代码如下:
/**
* 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 * * * * MON-SAT")
//@Scheduled(cron = "0,1,2,3,4 * * * * MON-SAT")
// @Scheduled(cron = "0-4 * * * * MON-SAT")
@Scheduled(cron = "0/4 * * * * MON-SAT") //每4秒执行一次
public void hello(){
System.out.println("hello ... ");
}
3. 邮件任务
SpringBoot也有对邮件任务的支持,使用起来也很方便:
-
在pom.xml中引入依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
-
在application.properties中配置邮件服务的相关属性:
#配置发送邮件的用户名 spring.mail.username=xxxxxxxxx@qq.com #用QQ邮箱服务发送需要配置授权码 spring.mail.password=xxxxxxxxxxx #指定邮件服务器的地址 spring.mail.host=smtp.qq.com #使用QQ邮件服务需要开启ssl支持 spring.mail.properties.mail.smtp.ssl.enable=true
-
接下来就可以发送邮件了,代码如下:
/* *SpringBoot为我们自动配置了发送邮件的组件,我们直接注入使用即可 */ @Autowired JavaMailSenderImpl mailSender; /* *发送简单的邮件信息(不包含文件附件) */ @Test public void contextLoads() { SimpleMailMessage message = new SimpleMailMessage(); //设置邮件信息 message.setSubject("这是一个测试邮件");//标题 message.setText("hello word!");//内容 message.setTo("xxxxxxxx@163.com");//接收人的邮箱地址 message.setFrom("xxxxxxxx@qq.com");//发送人的邮箱地址 //发送邮件 mailSender.send(message); } /* *发送复杂的邮件(带附件) */ @Test public void test02() throws Exception{ //1、创建一个复杂的消息邮件 MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); //邮件设置 helper.setSubject("这是复杂邮件的测试"); //setText的第二个属性可以开启HTML语法支持,这样我们就可以编写HTML信息来发送 helper.setText("<b style='color:red'>hello word</b>",true); helper.setTo("xxxxxxx@163.com"); helper.setFrom("xxxxxxxx@qq.com"); //上传附件,可以上传多个 helper.addAttachment("1.jpg",new File("C:\\Users\\xxx\\Pictures\\Saved Pictures\\1.jpg")); helper.addAttachment("2.jpg",new File("C:\\Users\\xxx\\Pictures\\Saved Pictures\\2.jpg")); mailSender.send(mimeMessage); }
总结
可以看到,使用了SpringBoot以后,我们直接使用自动配置的配置类来操作数据即可,不用像以前一样自己封装对应的组件.