任务
1、异步任务
开启
@SpringBootApplication
@EnableAsync
public class Demo14Application {
public static void main(String[] args) {
SpringApplication.run(Demo14Application.class, args);
}
}
使用
@Async
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
2、邮件任务
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
配置
spring.mail.username=2530942753@qq.com
spring.mail.password=seamfpgsfjthdhgc
spring.mail.host=smtp.qq.com
#开启加密验证
spring.mail.properties.mail.smtp.ssl.enable=true
使用
@Test
void contextLoads() {
//发送一个简单的邮件
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setSubject("Yan");
simpleMailMessage.setText("hello Yan");
simpleMailMessage.setFrom("2530942753@qq.com");
simpleMailMessage.setTo("2530942753@qq.com");
mailSender.send(simpleMailMessage);
}
@Test
void contextLoads1() throws MessagingException {
//发送一个复杂的邮件
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
helper.setSubject("Yan");
helper.setText("hello Yan");
helper.setFrom("2530942753@qq.com");
helper.setTo("2530942753@qq.com");
helper.addAttachment("20201022160116.png", new File("C:\\Users\\Alex Mercer\\Desktop\\20201022160116.png"));
mailSender.send(mimeMessage);
}
3、定时任务
TaskExecutor
TaskScheduler
开启
@SpringBootApplication
@EnableScheduling
public class Demo14Application {
public static void main(String[] args) {
SpringApplication.run(Demo14Application.class, args);
}
}
使用
@Service
public class HelloService {
@Scheduled(cron = "0/2 * * * * ?")
public void hello(){
System.out.println("hello");
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?