SpringBoot与任务

1.异步任务

通常情况下,java执行代码都是同步处理的,在一些需要异步的场景则需要使用多线程的方式,编码难度增大。

总的来说,通过@Async注解可以达到异步处理方法的目的。如下实例:

AsyncService.java

@Service
public class AsyncService {

    /**
     * 执行任务,3秒钟之后才打印数据
     */
    @Async //表示这是一个异步方法,执行到此方法时spring会自动创建线程去执行,而不需要等待
    public void task(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("数据处理中......");
    }
}

AsyncController.java

@RestController
public class AsyncController {

    @Autowired
    AsyncService asyncService;

    @GetMapping("/async")
    public String testAsync(){
        asyncService.task();
        return "success";
    }
}

Application.java

@EnableAsync //开启异步注解
public class SpringBootDemoApplication {

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

}

2.定时任务

使用@Scheduled@EnableScheduling两个注解可以实现定时任务。如下:

@Service
public class ScheduleService {

    /**
     * cron表达式规则 秒 分 时 日期 月份 星期
     */
    @Scheduled(cron = "*/30 * * * * *") //每30秒执行一次
    public void helloSchedule(){
        System.out.println(new Date() + ": 执行.......");
    }
}
@EnableScheduling //开启定时任务
public class SpringBootDemoApplication {

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

}

cron表达式规则

crontab表达式规则

cron表达式

参考文章:cron表达式详解

3.邮件任务

1.引入starter

<!--引入SpringBoot mail邮件功能-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2.配置发送邮箱

spring: 
	mail:
        host: smtp.qq.com
        username: 1******46@qq.com
        password: njbnludor******* #需要到QQ邮箱中随机生成
        properties.mail.smtp.ssl.enable: true

3.发送邮件

@Autowired
private JavaMailSenderImpl mailSender;

//发送简单邮件
@Test
public void sendSimpleMall(){
    SimpleMailMessage message = new SimpleMailMessage();
    message.setSubject("测试标题");
    message.setText("测试内容");
    message.setTo("y******6@163.com");
    message.setFrom("1*******6@qq.com");
    mailSender.send(message);
}

//发送复杂邮件
//附件
//格式
@Test
public void sendMimeMail() throws MessagingException {
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);//复杂邮件
    helper.addAttachment("dns.png",new File("f:\\dns.png"));//添加附件
    helper.addAttachment("个人文件.txt",new File("f:\\个人文件.txt"));
    helper.setSubject("测试复杂邮件");
    helper.setText("<h1 style='color:red'>附件是两个文件</h1>",true);
    //接收人和发送人信息不可少
    helper.setTo("y******6@163.com");
    helper.setFrom("1******6@qq.com");
    mailSender.send(mimeMessage);
}
posted @ 2021-12-15 15:49  lavendor  阅读(44)  评论(0)    收藏  举报