一、异步任务
需要的注解:@Async和@EnableAsync
java的代码是同步顺序执行,当我们需要执行异步操作时我们需要创建一个新线程去执行
@Service
public class AsyncService {
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.err.println("异步任务。。。");
}
}
@RequestMapping("/hello")
public String hello(){
System.err.println("先执行代码");
asyncService.hello();
return "hello....";
}
页面请求会等待返回信息,直到3秒后,接收到返回信息。
2、如何实现异步:
实现异步效果:页面请求返回信息,后台等待执行service的hello方法。
@Async
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.err.println("异步任务。。。");
}
@EnableAsync
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
二、定时任务
需要的注解:@EnableScheduling和@Scheduled
在定时执行的方法上添加注解@Scheduled,再在启动器上添加@EnableScheduling
@Service
public class taskJob {
@Scheduled(cron = "0/3 * * * * ?")
public void saveScheduled(){
System.err.println("定时");
}
}
@EnableScheduling
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
三、邮件任务
1、邮件发送需要引入spring-boot-starter-mail
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2、添加配置信息
spring.mail.username=xxxxx@qq.com
spring.mail.password=xxxxx 第三方授权码
spring.mail.host=smtp.qq.com
spring.mail.properties.mail.smtp.ssl.enable=true
3、编写类
@Autowired
JavaMailSenderImpl mailSender;
@Test
void contextLoads() {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setSubject("公告通知");
mailMessage.setText("今日停水");
mailMessage.setTo("1513xxx@163.com");
mailSender.send(mailMessage);
}
//复杂邮件(包含附件)
@Test
void test01() throws Exception {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setSubject("公告通知");
helper.setText("<b style='color:red;'>打法是的噶啥公司大</b>", true);
helper.setTo("15131182486@163.com");
//上传文件
helper.addAttachment("1.jpg", new File("url"));
mailSender.send(mimeMessage);
}