一、异步任务
通过spring的两个注解实现
@Async //在异步方法上标注此注解,告诉spring这是一个异步方法
@EnableAsync //在springboot启动类中标注此注解,开启异步注解功能
@Service
public class AsynService {
@Async
public void AsynMethod(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据处理成功");
}
}
@EnableAsync
@SpringBootApplication
public class SpringbootTestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootTestApplication.class, args);
}
}
二、邮件任务
邮件发送的两种方式:POP3/SMTP
导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
以QQ邮箱为例
点击开启获取授权码
配置
#用户名
spring.mail.username=45331533@qq.com
#授权码
spring.mail.password=akgfahplepakbghd
#授权的主机如果是163就163.com
spring.mail.host=smtp.qq.com
#QQ有特殊的加密规则 需要开启加密验证
spring.mail.properties.mail.smtp.ssl.enable=true
@SpringBootTest
class SpringbootTestApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
void contextLoads() {
//发送简单的邮件消息
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("通知");//主题
message.setText("好好学习,天天向上");//内容
message.setFrom("45331533@qq.com");//发送人
message.setTo("45331533@qq.com");//接收人
mailSender.send(message);
}
@Test
void contextLoads2() throws MessagingException {
//发送复杂的邮件消息
MimeMessage mimeMessage = mailSender.createMimeMessage();
//组装
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
helper.setSubject("通知plus");
helper.setText("<p style='color:red'>好好学习,天天向上plus</p>",true);
// 附件
helper.addAttachment("1.png",new File("C:\\Users\\86183\\Desktop\\捕获.png"));
helper.setFrom("45331533@qq.com");
helper.setTo("45331533@qq.com");
mailSender.send(mimeMessage);
}
}
三、定时任务
spring提供的两个定时任务的接口
TaskScheduler #任务调度者
TaskExecutor #任务执行者
@EnableScheduling #在springboot启动类中标注此注解,开启定时功能
@Scheduled #什么时候执行,在此注解中需要通过cron表达式来设置什么时候执行
@EnableScheduling
@SpringBootApplication
public class SpringbootTestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootTestApplication.class, args);
}
}
@Service
public class ScheduledService {
//在一个特定的时间执行这个方法
//cron表达式
//秒 分 时 日 月 周
@Scheduled(cron = "0/2 * * * * 0-7")
public void hello(){
System.out.println("你被执行了");
}
}