SpringBoot-任務

任務

1. 異步任務

1. 在須要異步的方法上添加註解

package com.wang.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncService {

    //告訴Spring這是異步的方法(多線程)
    @Async
    public void hello() {

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("數據正在處理......");

    }
}

@Asynchtml

2. 在main方法上開啓異步功能

package com.wang;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication
//開啓異步方法的註解
@EnableAsync
public class Springboot07TaskApplication {

    public static void main(String[] args) {
        SpringApplication.run(Springboot07TaskApplication.class, args);
    }

}

@EnableAsyncjava

效果: 跳轉不會受到異步任務的影響spring

2. 郵件任務

1. 添加依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2. 配置文件

spring:
  mail:
    username: 715180879@qq.com
    password: XXXXXX
    host: smtp.qq.com
    #開啓加密驗證(QQ郵箱要求) mail.smtp.ssl.enable: true
    properties:
      mail:
        smtp:
          ssl:
            enable: true

3. 郵件發送

在SpringBoot中, 郵件發送已經被封裝成JavaMailSenderImpl多線程

1. 簡單的郵件發送

@SpringBootTest
class Springboot07TaskApplicationTests {

    //在SpringBoot中JavaMailSenderImpl封裝了郵件發送的方法, 自動裝配便可使用
    @Autowired
    JavaMailSenderImpl mailSender;

    @Test
    void contextLoads() {

        //一個簡單的郵件 (只有文字)
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();

        //標題
        simpleMailMessage.setSubject("Hello My QQ Mail!");
        //正文
        simpleMailMessage.setText("這裏是正文!");
        //設置收發地址
        simpleMailMessage.setTo("715180879@qq.com");
        simpleMailMessage.setFrom("715180879@qq.com");

        //發送郵件
        mailSender.send(simpleMailMessage);
    }

}

2. 複雜郵件的發送

@SpringBootTest
class Springboot07TaskApplicationTests {

    //在SpringBoot中JavaMailSenderImpl封裝了郵件發送的方法, 自動裝配便可使用
    @Autowired
    JavaMailSenderImpl mailSender;

    @Test
    void contextLoads2() throws MessagingException {

        //一個複雜的郵件, 能夠經過mailSender的createMimeMessage方法建立一個MimeMessage
        MimeMessage message = mailSender.createMimeMessage();

        //組裝, 利用SpringBoot提供的 MimeMessageHelper, boolean能夠設置是否支持多文件
        MimeMessageHelper helper = new MimeMessageHelper(message,true);

        helper.setSubject("Hello My QQ Mail! Again!");
        //設置True支持Html標籤
        helper.setText("<p style='color:red'>這裏是正文!</p>",true);

        //附件, 使用絕對路徑
        helper.addAttachment("pic.jpg", new File("C:\\Users\\Wang\\Pictures\\Saved Pictures\\pic.jpg"));

        //設置收發地址
        helper.setTo("715180879@qq.com");
        helper.setFrom("715180879@qq.com");

        mailSender.send(message);
    }

}

3. 郵件發送功能的封裝與測試

@SpringBootTest
class Springboot07TaskApplicationTests {

    //在SpringBoot中JavaMailSenderImpl封裝了郵件發送的方法, 自動裝配便可使用
    @Autowired
    JavaMailSenderImpl mailSender;

    /**
     *
     * @param html : whether enable use html in text
     * @param multipart : whether enable send multiFiles
     * @param Subject : title of the mail
     * @param text : content of the mail
     * @param fileName : name for the attachment files
     * @param filePath : path for the attachment files, use abstract path
     * @param to : send the mail to someone
     * @param from : the mail from someone
     * @author Wang Sky
     */
    public void sendMail(Boolean html, Boolean multipart, String Subject, String text, String[] fileName,
                         String[] filePath, String to, String from) throws MessagingException {
        //一個複雜的郵件, 能夠經過mailSender的createMimeMessage方法建立一個MimeMessage
        MimeMessage message = mailSender.createMimeMessage();

        //組裝, 利用SpringBoot提供的 MimeMessageHelper, boolean能夠設置是否支持多文件
        MimeMessageHelper helper = new MimeMessageHelper(message,multipart);

        helper.setSubject(Subject);
        //設置True支持Html標籤
        helper.setText(text, html);

        //附件, 使用絕對路徑
        for (int i = 0; i < fileName.length; i++) {
            helper.addAttachment(fileName[i], new File(filePath[i]));
        }

        //設置收發地址
        helper.setTo(to);
        helper.setFrom(from);

        mailSender.send(message);
    }

    @Test
    void contextLoads3() throws MessagingException {

        String subject = "Hello My QQ Mail! Again!";
        String text = "<p style='color:red'>這裏是正文!</p>";
        String fileName1 = "pic.jpg";
        String filePath1 = "C:\\Users\\Wang\\Pictures\\Saved Pictures\\pic.jpg";
        String[] fileName = {fileName1};
        String[] filePath = {filePath1};
        String to = "715180879@qq.com";
        String from = "715180879@qq.com";

        sendMail(true, true, subject, text, fileName, filePath, to, from);
    }

}

3. 定時任務

兩個核心接口異步

  • TaskScheduler 任務調度
  • TaskExecutor 任務執行

核心註解spring-boot

  • @EnableScheduling 放在main方法上
  • @Scheduled 表示何時執行, 在定時任務的方法上

利用cron表達式設定執行時間測試

package com.wang.service;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class ScheduleService {

    //在一個特定的時間執行這個方法
    //cron表達式   sec min hour day month week     天天的10:43:00執行一次
    @Scheduled(cron = "0 43 10 * * ?")
    public void hello() {
        System.out.println("hello, 你被執行了!");
    }
}
相關文章
相關標籤/搜索