SpringBoot 学习(八)异步任务,邮件发送和定时执行

8. 异步任务

(1) 开启异步注解

// 启动类
@EnableAsync
@SpringBootApplication
public class TestApplication {

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

}

(2) 声明异步方法

// service
@Service
public class AsyncService {

    // 声明此方法为异步方法
    @Async
    public void sleep() {

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

        System.out.println("数据正在处理...");

        SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
        Date edate = new Date(System.currentTimeMillis());
        System.out.println("edate:" + formater.format(edate));
    }
}

(3) 调用异步方法

// controller
@RestController
public class AsyncController {

    @Autowired
    AsyncService asyncService;

    @RequestMapping("/sleep")
    public String sleep() {
        SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
        Date sdate = new Date(System.currentTimeMillis());
        System.out.println("sdate:" + formater.format(sdate));
        asyncService.sleep();   // 休眠三秒,等待服务器响应
        return "OK";
    }
}

(4) 测试效果

在这里插入图片描述

在这里插入图片描述

9. 邮件发送

(1) 配置

# application.properties
spring.mail.username=1942953841@qq.com
spring.mail.password=wedahkcfqhwkfdcg
spring.mail.host=smtp.qq.com
# qq 邮箱开启加密验证
spring.mail.properties.mail.smtp.ssl.enable=true

(2) 测试

@Autowired
JavaMailSenderImpl mailSender;

// 测试简单邮件发送
@Test
void sendSimpleMail() {
    SimpleMailMessage mailMessage = new SimpleMailMessage();
    mailMessage.setSubject("Hello");
    mailMessage.setText("Nice to meet you !");
    mailMessage.setTo("[email protected]");
    mailMessage.setFrom("[email protected]");
    mailSender.send(mailMessage);
}

// 测试复杂邮件发送
@Test
void sendMimeMail() throws MessagingException {
    MimeMessage mimeMessage = mailSender.createMimeMessage();

    // 组装
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

    // 正文
    helper.setSubject("Hello");
    helper.setText("

Nice to meet you !

"
, true); // 附件 helper.addAttachment("鬼泣DMC.jpg", new File("C:\\Users\\LENOVO\\Pictures\\鬼泣DMC.jpg")); helper.setTo("[email protected]"); helper.setFrom("[email protected]"); mailSender.send(mimeMessage); }

10. 定时执行

(1) 启动定时注解

// 启动类
@EnableScheduling   // 开启定时功能
@SpringBootApplication
public class TestApplication {

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

}

(2) 测试

@Service
public class ScheduledService {

    // corn 表达式
    // 秒 分 时 日 月 星期
    @Scheduled(cron = "30 * * * * 0-7")
    public void timer30() {
        SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
        Date date = new Date(System.currentTimeMillis());
        System.out.println("Time is " + formater.format(date));
    }
}

SpringBoot 学习(八)异步任务,邮件发送和定时执行_第1张图片

你可能感兴趣的:(SpringBoot,spring,boot,学习,后端)