Title

异步、邮件、定时任务

1.异步任务

  1. 给进程加上注解

        @Async
        public void hello() throws InterruptedException {
            Thread.sleep(3000);
            System.out.println("数据正在处理....");
        }
    
  2. 开启异步注解功能

    @EnableAsync //开启异步注解功能
    @SpringBootApplication
    public class AsynTaskApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(AsynTaskApplication.class, args);
        }
    
    }
    

2.邮件任务

  1. 导入mail依赖

    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-mail -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
        <version>2.6.3</version>
    </dependency>
    
    1. 配置邮箱(邮箱也需要开启smtp服务协议)

      spring.mail.username=2233059353@qq.com
      spring.mail.password=zaavlavufkepebde
      spring.mail.host=smtp.qq.com
      #开启加密验证
      spring.mail.properties.mail.smto.ssl.enble=true
      

      简单的邮件:

      @SpringBootTest
      class SynTaskApplicationTests {
      
          @Autowired //spring自带一个邮件发送器
          JavaMailSenderImpl javaMailSender;
      
          @Test
          void contextLoads() {
              SimpleMailMessage mailMessage = new SimpleMailMessage();
              mailMessage.setSubject("title");
              mailMessage.setText("This is Content!");
              mailMessage.setFrom("2233059353@qq.com");
              mailMessage.setTo("2233059353@qq.com");
              javaMailSender.send(mailMessage);
          }
      
      }
      

      复杂的邮件:

        @Autowired //spring自带一个邮件发送器
          JavaMailSenderImpl javaMailSender; 
      @Test
          void contextLoads2() throws MessagingException {
              //复杂的邮件
              MimeMessage mimeMessage = javaMailSender.createMimeMessage();
              //组装
              MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
              helper.setSubject("title");
              helper.setText("<p style='color:red'>This is Content!</p>",true);
      
              helper.addAttachment("1.jpg",new File("C:\\Users\\阿羡\\Pictures\\Saved Pictures\\1.jpg"));
      
              helper.setFrom("2233059353@qq.com");
              helper.setTo("2233059353@qq.com");
              javaMailSender.send(mimeMessage);
      
          }
      

3.定时任务

@EnableScheduling
 //cron表达式
 //秒 分 时 日 月 周几
 @Scheduled(cron = "0 57 16 * * ?")
posted @ 2022-04-14 16:59  手中的小黄鸭  阅读(15)  评论(0)    收藏  举报