任务
1、异步任务
@SpringBootApplication
//开启异步注解的功能
@EnableAsync
public class SpringbootTaskApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootTaskApplication.class, args);
}
}
/**
* 异步任务
*/
@Service
public class AsyncService {
/**
* 告诉spring这是一个异步的方法
*/
@Async
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在处理...");
}
}
@RestController
public class AstncController {
@Autowired
AsyncService asyncService;
@RequestMapping("/hello")
public String hello(){
//停止3秒
asyncService.hello();
return "ok";
}
}
2、邮件发送
<!--邮件发送-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
spring.mail.username=xxx@qq.com
spring.mail.password=xxx
spring.mail.host=smtp.qq.com
# 开启加密验证
spring.mail.properties.mail.smtp.ssl.enable=true
package com.sjx.springboottask;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@SpringBootTest
class SpringbootTaskApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
void contextLoads() {
//一个简单的邮件
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setSubject("测试");
mailMessage.setText("使用springboot发送邮件....");
mailMessage.setTo("xxx@qq.com");
mailMessage.setFrom("xxx@qq.com");
mailSender.send(mailMessage);
}
@Test
void contextLoads2() 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("D:\\Desktop\\1.jpg"));
helper.setTo("xxx@qq.com");
helper.setFrom("xxx@qq.com");
mailSender.send(mimeMessage);
}
}
3、定时任务
TaskScheduler 任务调度者
TaskExecutor 任务执行者
@EnableScheduling //开启定时功能的注解
@Scheduled
@Service
public class ScheduledService {
/**
* cron 表达式
* 秒 分 时 日 月 周几~
* 0 14 16 * * ? 每天的16点14分 执行一次
* 0 0/5 16,17 * * ? 每天16点和17点,每隔5分钟执行一次
* 0 15 10 ? * 1-6 每个月的周一到周六 10点15执行一次
*/
@Scheduled(cron = "0 14 16 * * ?")
public void hello(){
System.out.println("hello,你被执行了");
}
}