SpringBoot 实现 异步任务、邮件发送任务、定时任务

写在前面(代码可直接运行)

  • 异步任务+邮件发送任务+定时任务:springboot-08-test
  • 如果觉得对您有帮助,请点个赞支持一下:

一. 异步任务

1.1 简介 - 何为异步任务

  • 异步任务,与同步任务相对。
  • 同步任务:等后台执行结束,前台在显示
  • 异步任务:前台先显示,后台继续在运行代码

1.2 代码实现

  • 在SpringBoot 主程序中开启异步注解 @EnableAsync
@EnableAsync //开启异步注解功能
@SpringBootApplication
public class Springboot08TestApplication {

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

}
  • 创建一个异步类 AsyncService(功能:延时3s,再执行代码
    给 hello 方法添加 @Async 注释
@Service
public class AsyncService {

    //告诉Spring这是一个异步方法
    @Async
    public void hello() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("数据正在处理。。。");
    }
}
  • 编写控制类- AsyncController
@RestController
public class AsyncController {
    @Autowired
    AsyncService asyncService;

    @RequestMapping("/hello")
    public String hello() {
        asyncService.hello();//停止三秒

        return "OK";
    }
}
  • 结果

访问 localhost:8080/hello 网站,前台先显示 OK,过了三秒,后台显示“数据正在处理。”

二. 邮件发送任务

2.1 一般步骤

邮件发送:

  • 邮件发送需要引入spring-boot-start-mail
  • SpringBoot 自动配置MailSenderAutoConfiguration
  • 定义MailProperties内容,配置在application.yml中
  • 自动装配JavaMailSender
  • 测试邮件发送

2.2 测试

  • Maven 导入 mail 包
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
  • 配置文件
spring.mail.username=635908933@qq.com
spring.mail.password=你的qq授权码
spring.mail.host=smtp.qq.com
# qq需要配置ssl
spring.mail.properties.mail.smtp.ssl.enable=true
  • 查看源码(明白配置文件应该怎么写)
@ConfigurationProperties(prefix = "spring.mail")
public class MailProperties {

	private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
	private String host;
	private Integer port;
	private String username;
	private String password;
	private String protocol = "smtp";
	private Charset defaultEncoding = DEFAULT_CHARSET;
	private Map<String, String> properties = new HashMap<>();
	private String jndiName;
	//set、get方法省略。。。
}

  • 获取授权码:在QQ邮箱中的设置->账户->开启pop3和smtp服务
    在这里插入图片描述

  • SpringBoot 单元测试

@Autowired
JavaMailSenderImpl javaMailSender;
@Test//邮件设置1:一个简单的邮件
void contextLoads() {
    SimpleMailMessage mailMessage = new SimpleMailMessage();
    mailMessage.setSubject("kc,你好");
    mailMessage.setText("Nice to meet you!!!");

    mailMessage.setTo("24736743@qq.com");
    mailMessage.setFrom("635908933@qq.com");
    javaMailSender.send(mailMessage);
}

@Test// 一个复杂的邮件
void contextLoads2() throws MessagingException {
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    //组装
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

    //正文
    helper.setSubject("kc,你好~plus");
    helper.setText("<p style='color:red'>Nice to meet you!!!</p>", true);

    //附件
    helper.addAttachment("1.jpg", new File(""));
    helper.addAttachment("2.jpg", new File(""));

    helper.setTo("24736743@qq.com");
    helper.setFrom("635908933@qq.com");

    javaMailSender.send(mimeMessage);

}

查看邮箱,邮件接收成功!

我们只需要使用 Thymeleaf 进行前后端结合即可开发自己网站邮件收发功能了!

三. 定时任务

3.1 简介

  • 项目开发中经常需要执行一些定时任务,比如需要在每天凌晨的时候,分析一次前一天的日志信息,Spring为我们提供了异步执行任务调度的方式,提供了两个接口。
  1. TaskExecutor 接口(任务执行者)
  2. TaskScheduler 接口(任务调度者)

两个注解:

  • @EnableScheduling ——开启定时功能的注解
  • @Scheduled ——什么时候执行

3.2 Cron 表达式

(1)0/2 * * * * ?   表示每2秒 执行任务
(1)0 0/2 * * * ?   表示每2分钟 执行任务
(1)0 0 2 1 * ?   表示在每月的1日的凌晨2点调整任务
(2)0 15 10 ? * MON-FRI   表示周一到周五每天上午10:15执行作业
(3)0 15 10 ? 6L 2002-2006   表示2002-2006年的每个月的最后一个星期五上午10:15执行作
(4)0 0 10,14,16 * * ?   每天上午10点,下午2点,4点
(5)0 0/30 9-17 * * ?   朝九晚五工作时间内每半小时
(6)0 0 12 ? * WED   表示每个星期三中午12点
(7)0 0 12 * * ?   每天中午12点触发
(8)0 15 10 ? * *   每天上午10:15触发
(9)0 15 10 * * ?     每天上午10:15触发
(10)0 15 10 * * ?   每天上午10:15触发
(11)0 15 10 * * ? 2005   2005年的每天上午10:15触发
(12)0 * 14 * * ?     在每天下午2点到下午2:59期间的每1分钟触发
(13)0 0/5 14 * * ?   在每天下午2点到下午2:55期间的每5分钟触发
(14)0 0/5 14,18 * * ?     在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发
(15)0 0-5 14 * * ?   在每天下午2点到下午2:05期间的每1分钟触发
(16)0 10,44 14 ? 3 WED   每年三月的星期三的下午2:10和2:44触发
(17)0 15 10 ? * MON-FRI   周一至周五的上午10:15触发
(18)0 15 10 15 * ?   每月15日上午10:15触发
(19)0 15 10 L * ?   每月最后一日的上午10:15触发
(20)0 15 10 ? * 6L   每月的最后一个星期五上午10:15触发
(21)0 15 10 ? * 6L 2002-2005   2002年至2005年的每月的最后一个星期五上午10:15触发
(22)0 15 10 ? * 6#3   每月的第三个星期五上午10:15触发

3.3 测试

  • 主程序中开启定时注释 – @EnableScheduling
@EnableAsync //开启异步注解功能
@EnableScheduling//开启异步定时功能的注解
@SpringBootApplication
public class Springboot08TestApplication {

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

}
  • 编写 ScheduledService 测试类
@Service
public class ScheduledService {

    // 在一个特定的时间执行这个方法——Timer
    //cron表达式
    // 秒 分 时 日 月 周几

    /*
        0 49 11 * * ?   每天的11点49分00秒执行
        0 0/5 11,12 * * ?   每天的11点和12点每个五分钟执行一次
        0 15 10 ? * 1-6     每个月的周一到周六的10点15分执行一次
        0/2 * * * * ?     每2秒执行一次
     */
    @Scheduled(cron = "0/2 * * * * ?")
    public void hello() {
        System.out.println("hello,你被执行了");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值