Async 任务
所谓异步任务就是开启多个线程处理一个请求,一个线程响应完成信息,一个线程处理业务, 这样很快,对客户来说
springboot 提供了两个注解 进行处理异步任务
@EnableAsync
@Async
@EnableAsync 标注启动类上表示启动异步注解方式
@Async 标注到需要异步处理的方法上,此方法为异步处理方法
@EnableAsync
@SpringBootApplication
public class SpringBoot04TaskApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBoot04TaskApplication.class, args);
}
}
@Async
public void hello(){
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("run public void hello()");
}
定时任务
springboot 提供两个注解 一个开启,一个标注
@EnableScheduling @Scheduling
要使用cron 表达式 代码如下
package com.zzq.springboot04task.service;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class SchedulingService {
@Scheduled(cron = "*/1 * * * * ?")
public void hello(){
System.out.println("hello!");
}
}
注意一定要在启动类上加上@EnableScheduling
邮件任务
引入starter
<!-- 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.0.4.RELEASE</version>
</dependency>
然后配置properties
spring.mail.username=zzql0vezll1314@163.com
spring.mail.password=zzqlvezll1314
spring.mail.host=smtp.163.com
spring.mail.properties.mail.smtp.ssl.enable=true
@Autowired
private JavaMailSender javaMailSender ;
@Test
public void contextLoads() {
SimpleMailMessage message = new SimpleMailMessage();
//邮箱设置
message.setSubject("通知:今晚开会");
message.setText("今晚7.30开会");
message.setTo("2766090785@qq.com");
message.setFrom("zzql0vezll1314@163.com");
javaMailSender.send(message);
}