异步任务
Service
@Service
public class AsyncService {
@Async //告诉spring这是一个异步方法
/**
*
## 开启异步之前 controller到了这个地方之后就会暂停三秒 开启了之后就不会暂停 而是新开一个线程去处理
*/
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Controller
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@GetMapping("/hello")
public String hello() {
asyncService.hello();
return "success";
}
}
启动类
@SpringBootApplication
@EnableAsync //开启异步注解功能
public class SpringbootmissionApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootmissionApplication.class, args);
}
}
定时启动
Service
/**
* on the second as well as minute, hour, day of month, month and day of week.
*
* {@code "0 * * * * MON-FRI"} 这个代表的是周一到周五整秒启动一次
* 空格为间隔
*
*/
// @Scheduled(cron = "* * * * * MON-FRI")
// @Scheduled(cron = "")
public void helloOnTime(){
System.out.println("hello ");
}
启动类上加一个注解@EnableScheduling //开启定时启动功能
发送邮件
引入邮件的starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
/**
* 简单邮件
* 只能发送文本
*/
@Autowired
JavaMailSenderImpl javaMailSender;
@Test
public void context(){
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setSubject("通知-何豆豆是猪");
mailMessage.setText("<a href=\"http://www.baidu.com\">百度</a>");
mailMessage.setTo("dailinfeng66@163.com");
mailMessage.setFrom("2441086385@qq.com");
javaMailSender.send(mailMessage);
}
/**
* 复杂邮件 能够发送文本 HTML 以及文件
* @throws MessagingException
*/
@Test
public void Test02() throws MessagingException {
//创建一个复杂的消息邮件
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
//邮件设置
helper.setSubject("通知-何豆豆是猪");
helper.setText("<a href=\"http://www.baidu.com\">百度</a>",true); //第二个参数 public void setText(String text, boolean html) throws MessagingException
helper.setTo("dailinfeng66@163.com");
helper.setFrom("2441086385@qq.com");
//上传文件
helper.addAttachment("1.png",new File("C:\\Users\\Administrator\\Pictures\\Screenshots\\屏幕截图(24).png"));
helper.addAttachment("照片2.jpg",new File("G:\\D盘\\diannaobizhi\\img08.jpg"));
javaMailSender.send(mimeMessage);
}