SpringBoot开启任务(异步任务、定时任务、邮件任务)

Java知识点总结:想看的可以从这里进入

2.20、开启任务

2.20.1、异步任务

可以让程序新开一个线程去执行该任务,而使用户在使用时界面不会因为程序而卡顿

  • 在springboot的启动类中添加开启异步任务的注解

    @SpringBootApplication
    @EnableAsync	//开启异步的支持
    public class SpringbootdemoApplication {
          
          
    }
    
  • 在controller方法中添加异步的注解

    @Async	//进行异步处理
    @RequestMapping("/test")
    public String test(Model model){
          
          
      	..........
    }
    

2.20.2、定时任务

  • 开启支持定时任务的注解

    @SpringBootApplication
    @EnableScheduling
    public class SpringbootdemoApplication {
          
          
    }
    
  • 使用 @Scheduled(cron=“秒分时日月周几”)注解 来设置什么时候执行

    @Scheduled(cron = "秒 分 时 日 月 周几")
    public void test(){
          
          
        System.out.println("执行了");
    }
    

定时任务中需要用到cron 表达式

2.20.3、邮件任务

  • 添加依赖

    <!--开启邮箱任务-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
    
  • 在yml文件中配置发送邮箱的信息

    spring:
     mail:
      username: [email protected]   #邮箱名
      password:            #IMAP/SMTP服务获取的密码
      host: smtp.163.com    #主机
      properties:      #加密验证
        mail:
          smtp:
            ssl:
              enable: true
    
  • 编写发送邮件的方法

    @Autowired
    private JavaMailSenderImpl javaMailSender;
    @Test
    void test() {
          
          
        SimpleMailMessage message = new SimpleMailMessage();
        //内容
        message.setSubject("尊敬的用户你好!");		//标题
        message.setText("恭喜你收到这份邮件,祝你好运 ");	//内容
        
        message.setTo("");	//发给谁
        message.setFrom("");	//谁发的
        javaMailSender.send(message);
    }
    
    image-20210902223424171
  • 带附件的邮箱

    @Test
    void test2() throws MessagingException {
          
          
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
    
        helper.setSubject("尊敬的用户你好!");
        helper.setText("<h1>恭喜你收到这份邮件,支持html标签</h1>",true);
    	//附件
        helper.addAttachment("1.txt",new File("C:/Users/羽/Desktop/1.txt"));
    
        helper.setTo("");	//发给谁
        helper.setFrom("");	//谁发的
        javaMailSender.send(mimeMessage);
    }
    
    image-20210902224719132

猜你喜欢

转载自blog.csdn.net/yuandfeng/article/details/129727507