异步任务
模拟一个任务
@Service
public class AsyncService {
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在等待执行....");
}
}
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@RequestMapping("/hello")
public String hello(){
asyncService.hello();//停止三秒
return "OK";
}
}
这个时候程序就会等待三秒,程序才会打印下面的任务,如果我们加异步就会各执行各的。
开启异步任务,总共就两步:
①在方法上加异步注解
②在主方法上加EnableAsync开启异步
@Service
public class AsyncService {
@Async
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在等待执行....");
}
}
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@RequestMapping("/hello")
public String hello(){
asyncService.hello();//停止三秒
return "OK";
}
}
@EnableAsync
@SpringBootApplication
public class Springboot09TestApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot09TestApplication.class, args);
}
}
邮件任务
application.properties
spring.mail.username=763857320@qq.com
spring.mail.password=gwqcbjeznxzpbbfg
spring.mail.host=smtp.qq.com
#开启加密验证
spring.mail.properties.mail.smtp.ssl.enable=true
简单的邮件
测试类
@SpringBootTest
class Springboot09TestApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
void contextLoads() {
//一个简单的邮件
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("Hello Acoffee!");
message.setText("历遍山河,仍觉人间值得!");
message.setTo("[email protected]");
message.setFrom("[email protected]");
mailSender.send(message);
}
}
复杂的邮件
@Test
void contextLoad2() throws MessagingException {
//复杂的邮件
MimeMessage mimeMessage = mailSender.createMimeMessage();
//组装
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
helper.setSubject("欢迎您~~");
helper.setText("<p style='color:red'>你好啊~~</p>",true);
//附件
helper.addAttachment("1.jpg",new File("C:\\Users\\acoffee\\Desktop\\favicon.ico"));
helper.addAttachment("2.jpg",new File("C:\\Users\\acoffee\\Desktop\\favicon.ico"));
helper.setTo("[email protected]");
helper.setFrom("[email protected]");
mailSender.send(mimeMessage);
}
定时任务
代码 | 含义 |
---|---|
TaskScheduler | 任务调度者 |
TaskExecutor | 任务执行者 |
@EnableScheduling | 开启定时功能注解 |
@Scheduled | 什么时候执行 |
在 @Scheduled
后面使用cron表达式表示执行的时间
@Service
public class ScheduledService {
//在特定的时间执行
@Scheduled(cron = "30 15 10 * * ?")
public void hello(){
System.out.println("Hello World~~");
}
}