SpringBoot 2.1.x整合Task任务相关示例

Async异步任务

  • 主启动类添加@EnableAsync注解
  • 方法上添加@Async注解
 @Async
 public void async_task01() {
     try {
         Thread.sleep(3000);
     } catch (Exception e) {
         e.printStackTrace();
     }
     System.out.println("async_task01(),执行完毕!!");
 }

Scheduled定时任务

  • 主启动类添加@EnableScheduling注解
  • 方法上添加@Scheduled注解
    /**
     * second(秒) minute(分) hour(时) day(日) month(月) week(周).
     * "0 * * * * MON-FRI"
     */
    @Scheduled(cron = "*/10 * * * * *")
    @Override
    public void hello() {
        System.out.println("开始执行定时任务....");
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }

在这里插入图片描述

Mail邮件任务

  • pom.xml
<!--邮件任务-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
  • application.yml
#Mail配置相关
spring:
  mail:
    username: liuyi@163.com
    password: asdfghj123456
    host: smtp.163.com
  • 简单Mail发送
@Autowired
JavaMailSenderImpl javaMailSender;

@Override
public void sendEmail() {
    //简单消息
    SimpleMailMessage message = new SimpleMailMessage();

    //邮件设置
    message.setSubject("通知-今晚开会");
    message.setText("重要!特别通知!今晚19:30在会议上进行批斗大会");
    message.setTo("yx*********@163.com");
    message.setFrom("yx*********@163.com");
    javaMailSender.send(message);

}

在这里插入图片描述

  • 复杂Mail发送
 public void sendComplexEmail() throws Exception {
      //1、创建一个复杂的消息邮件
       MimeMessage mimeMessage = javaMailSender.createMimeMessage();
       MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

       //邮件设置
       helper.setSubject("通知-今晚开会");
       helper.setText("<b style='color:red'>重要!特别通知!今晚19:30在会议上进行批斗大会</b>",true);

       helper.setTo("yx*********@163.com");
       helper.setFrom("yx*********@163.com");

       //上传文件
       helper.addAttachment("1.jpg",new File("F:\\icon\\1.jpg"));
       helper.addAttachment("2.jpg",new File("F:\\icon\\2.jpg"));

       javaMailSender.send(mimeMessage);

    }

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值