1. 程式人生 > >springboot(十一)SpringBoot任務

springboot(十一)SpringBoot任務

dem wire des help 附件 oot bject ace 設置

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)\">\n" + "通過 rbg 值設置背景顏色\n" + "</p>\n" + "<p style=\"background-color:rgba(255,255,0,0.25)\">\n" + "通過 rbg 值設置背景顏色\n" + "</p>\n" + "<p style=\"background-color:rgba(255,255,0,0.5)\">\n" + "通過 rbg 值設置背景顏色\n" + "</p>\n" + "<p style=\"background-color:rgba(255,255,0,0.75)\">\n" + "通過 rbg 值設置背景顏色\n" + "</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(); } } }

springboot(十一)SpringBoot任務