任务处理(异步任务,邮件任务,计划任务)

异步任务

通过注解实现简单的异步任务

编写service和controller,service类加入@Async注解,启动类加入@EnableAsync注解开启异步功能

@Service
public class AsyncService {
    @Async
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("数据正在处理");

    }

}
@Controller
public class AsyncController {

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

测试结果,页面没有等待直接返回了ok,使用了异步任务没有因为执行hello方法而等待三秒

邮件任务

导入依赖

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

开启邮箱的SMTP客户端配置,获取加密密码用于发送邮件的配置

编写application邮件配置

spring.mail.username=xxx@qq.com
#使用加密密码
spring.mail.password=xxx spring.mail.host=smtp.qq.com

编写发送简单邮件的测试类

    @Autowired
    MailSender mailSender;

    @Test
    void contextLoads() {
        SimpleMailMessage smm = new SimpleMailMessage();
        smm.setSubject("java发送邮件");
        smm.setText("邮件发送成功");
        smm.setTo("924563151@qq.com");
        smm.setFrom("924563151@qq.com");
        mailSender.send(smm);

    }

编写发送复杂邮件的测试类

 测试结果,邮箱收到邮件

计划任务

 

启动类增加注解@EnableScheduling开启计划任务功能

在需要执行的方法上使用@Scheduled注解,并使用Cron表达式

编写发送简单邮件的测试类

原文地址:https://www.cnblogs.com/alanchenjh/p/12349070.html