springbootSpringBoot任务
Posted Brian Huang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springbootSpringBoot任务相关的知识,希望对你有一定的参考价值。
github地址: https://github.com/showkawa/springBoot_2017/tree/master/spb-demo
1. 异步任务
方法名加上注解@Async,在启动类上加上@EnableAsync
@Async public void brianAsync(){ try { Thread.sleep(3000); brianMail.sendEmail(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("异步任务"); }
2.定时器任务
方法名加上注解@Scheduled,在启动类上加上@EnableScheduling,最主要的掌握正则表达式的规则
@Scheduled(cron = "0 * * * * *") public void brianScheduling() { System.out.println("定时任务"); }
3.邮件任务
package com.kawa.mail; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.File; @Service public class BrianMail { @Autowired JavaMailSenderImpl javaMailSender; public void sendEmail() { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); try { //multipart:true表示开启附件添加 MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); //邮件设置 mimeMessageHelper.setSubject("测试邮件"); mimeMessageHelper.setText("<p style="background-color:rgb(255,255,0)"> " + "通过 rbg 值设置背景颜色 " + "</p> " + "<p style="background-color:rgba(255,255,0,0.25)"> " + "通过 rbg 值设置背景颜色 " + "</p> " + "<p style="background-color:rgba(255,255,0,0.5)"> " + "通过 rbg 值设置背景颜色 " + "</p> " + "<p style="background-color:rgba(255,255,0,0.75)"> " + "通过 rbg 值设置背景颜色 " + "</p>",true); mimeMessageHelper.setFrom("[email protected]"); mimeMessageHelper.setTo("[email protected]"); mimeMessageHelper.setCc("[email protected]"); //附件 mimeMessageHelper.addAttachment("10086.jpg",new File("C:\Users\HYHGHHHH\Desktop\backup\10086.jpg")); javaMailSender.send(mimeMessage); System.out.println("邮件发送成功..."); } catch (MessagingException e) { e.printStackTrace(); } } }
以上是关于springbootSpringBoot任务的主要内容,如果未能解决你的问题,请参考以下文章