实验十二 Spring Boot 任务管理
一、 实验目的
1.使用 Spring Boot 完成异步任务、定时任务以及邮件任务。
二、 实验内容
1.熟悉 Spring Boot 整合异步任务的实现
2.熟悉 Spring Boot 整合定时任务的实现
3.熟悉 Spring Boot 整合邮件任务的实现
三、 实验步骤及截图
1. 使用 Idea+Maven 新建项目,并进行必要配置。
2. 编写入口类,并启用计划任务。
@EnableScheduling
@SpringBootApplication
public class ChapterAsync_LWL {
public static void main(String[] args){
SpringApplication.run(ChapterAsync_LWL.class,args);
}
}
3. 在 service 类,编写方法测试 cron 定时任务。
// 简单的定时任务
@Scheduled(cron = "10 * * * * *")
public void Task01(){
System.out.println("*********** 每 分 钟 的 第 10S 启 动 !
*********"+simpleDateFormat.format(new Date()));
}
4. 在 service 类,编写方法测试 fixedDelay 定时任务。
//delay 从第一次开始就计算间隔时间
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd
HH:mm:ss");
int index = 1;
@Scheduled(fixedDelay = 10000)
public void Task02(){
System.out.println("***********Task02 任 务 第 "+index+" 启 动 !
*********"+simpleDateFormat.format(new Date()));
try{
Thread.sleep(5000);
}catch (Exception e){
System.out.println("错误!");
}
System.out.println("***********Task02 任 务 第 "+index+" 结 束 !
*********"+simpleDateFormat.format(new Date()));
index++;
}
5. 在 service 类,编写方法测试 fixedRate 定时任务。
//rate 从第一次开始就计算间隔时间
@Scheduled(fixedRate = 10000)
public void Task03(){
System.out.println("***********Task03 任 务 第 "+index+" 启 动 !
*********"+simpleDateFormat.format(new Date()));
try{
Thread.sleep(5000);
}catch (Exception e){
System.out.println("错误!");
}
System.out.println("***********Task03 任 务 第 "+index+" 结 束 !
*********"+simpleDateFormat.format(new Date()));
index++;
}
6. 编写 controller 类,添加 sendSms 方法,调用无返回值的 service 方法。