异步、定时、邮件任务

异步任务

主要是两个注解@Async,@EnableAsync

@Service
public class AsyncService {

    @Async   //    告诉spring这是一个异步任务
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("数据加载中。。。");
    }
}
@RestController
public class AsyncController {

    @Autowired
    AsyncService asyncService;

    @RequestMapping("/hello")
    public String hello(){
        asyncService.hello();
        return "ok";
    }
}

@SpringBootApplication
@EnableAsync //开启异步注解任务
public class Springboot08TestApplication {

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

}

邮件任务

1、先导入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

2、开启QQ邮箱POP3/SMTP服务然后写配置

spring.mail.username=2010871025@qq.com
spring.mail.password=ytdgpufsjguqdbdc
spring.mail.host=smtp.qq.com
# 开启加密验证
spring.mail.properties.mail.smtp.ssl.enable=true

3、测试使用(也可以简单封装成一个工具类,方便使用)

@SpringBootTest
class Springboot08TestApplicationTests {

    @Autowired
    JavaMailSender javaMailSender;

    @Test
    void contextLoads() {

        //一个简单的邮件
        SimpleMailMessage simpleMailMessage=new SimpleMailMessage();
        simpleMailMessage.setSubject("hello,Fan");
        simpleMailMessage.setText("今天是2023/1/29,我在学springboot邮件任务");
        simpleMailMessage.setTo("2010871025@qq.com");
        simpleMailMessage.setFrom("2010871025@qq.com");

        javaMailSender.send(simpleMailMessage);
    }

    @Test
    void contextLoads2() throws MessagingException {

        //一个复杂的邮件
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //组装
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
        helper.setSubject("hello,FanPlus");
        helper.setText("<p style='color:red'>今天是2023/1/29,我在学springboot邮件任务Plus</p>",true);
//        附件
        helper.addAttachment("2.jpg",new File("G:\\image\\2.jpg"));
        helper.setTo("2010871025@qq.com");
        helper.setFrom("2010871025@qq.com");
        javaMailSender.send(mimeMessage);

    }
}

定时任务

TaskScheduler 任务调度者
TaskExecutor 任务执行者
@EnableScheduling  //开启定时任务注解
@Scheduled  //什么时候执行
@SpringBootApplication
@EnableAsync //开启异步任务注解
@EnableScheduling //开启定时任务注解
public class Springboot08TestApplication {

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

}

@Service
public class ScheduledService {

//    cron表达式,不会就问度娘
//    秒 分 时 日 月 周几
    @Scheduled(cron = "0/5 * * * * *")
    public void hello(){
        System.out.println("hello()被执行了...");
    }
}

posted @ 2023-01-29 18:05  Fannaa  阅读(17)  评论(0)    收藏  举报