一.项目环境
springboot2.x本身已经集成了定时任务模块和异步任务,可以直接使用
二.springboot常用定时任务配置
1.在启动类上使用注解@EnableScheduling开启定时任务,使用@EnableAsync开启异步任务
@SpringBootApplication //一个注解顶下面3个
@EnableScheduling //开启定时任务
@EnableAsync //开启异步任务
public class XdclassApplication {
public static void main(String[] args) {
SpringApplication.run(XdclassApplication.class, args);
}
}
2.使用注解@Schedule声明这是一个定时任务,Springboot启动会扫描到该注解并标记为定时任务
@Component
public class TestTask {
@Scheduled(cron="*/1 * * * * *")
public void sum2(){
System.out.println("cron 每秒 当前时间:"+new Date());
}
}
3.使用@Asyn声明这是一个异步任务的方法,如果在类上使用该注解,则该类下所有方法都是异步任务的方法
@Component
@Async
public class AsyncTask {
public void task1() throws InterruptedException{
long begin = System.currentTimeMillis();
Thread.sleep(1000L);
long end = System.currentTimeMillis();
System.out.println("任务1耗时="+(end-begin));
}
public void task2() throws InterruptedException{
long begin = System.currentTimeMillis();
Thread.sleep(2000L);
long end = System.currentTimeMillis();
System.out.println("任务2耗时="+(end-begin));
}
public void task3() throws InterruptedException{
long begin = System.currentTimeMillis();
Thread.sleep(3000L);
long end = System.currentTimeMillis();
System.out.println("任务3耗时="+(end-begin));
}
//获取异步结果
public Future<String> task4() throws InterruptedException{
long begin = System.currentTimeMillis();
Thread.sleep(2000L);
long end = System.currentTimeMillis();
System.out.println("任务4耗时="+(end-begin));
return new AsyncResult<String>("任务4");
}
public Future<String> task5() throws InterruptedException{
long begin = System.currentTimeMillis();
Thread.sleep(3000L);
long end = System.currentTimeMillis();
System.out.println("任务5耗时="+(end-begin));
return new AsyncResult<String>("任务5");
}
public Future<String> task6() throws InterruptedException{
long begin = System.currentTimeMillis();
Thread.sleep(1000L);
long end = System.currentTimeMillis();
System.out.println("任务6耗时="+(end-begin));
return new AsyncResult<String>("任务6");
}
}
测试
@RestController
@RequestMapping("/api/v1")
public class UserController {
@Autowired
private AsyncTask task;
@GetMapping("async_task")
public JsonData exeTask() throws InterruptedException{
long begin = System.currentTimeMillis();
// task.task1();
// task.task2();
// task.task3();
Future<String> task4 = task.task4();
Future<String> task5 = task.task5();
Future<String> task6 = task.task6();
//这里死循环让主线程挂起,目的是为了计算其他异步任务的执行任务的耗时
for(;;){
if (task4.isDone() && task5.isDone() && task6.isDone()) {
break;
}
}
long end = System.currentTimeMillis();
long total = end-begin;
System.out.println("执行总耗时="+total);
return JsonData.buildSuccess(total);
}
}