1 定时任务和异步任务
java.util.Timer; Quartz框架;SpringBoot
框架⾃带
注解⽅式开启定时任务
启动类⾥⾯
@EnableScheduling
开启定时任务,⾃动扫描
定时任务业务类加注解
@Component
被容器扫描
定时执⾏的⽅法加上注解
@Scheduled(fifixedRate=1000)
定期执⾏⼀次
cron
定时任务表达式
@Scheduled(cron="*/1 * * * * *")
表示每秒
crontab
⼯具
https://tool.lu/crontab/
fifixedRate:
定时多久执⾏⼀次(上⼀次开始执⾏时间点后
xx
秒再次执⾏;)
fifixedDelay:
上⼀次执⾏结束时间点后
xx
秒再次执⾏
异步任务
启动类⾥⾯使⽤
@EnableAsync
注解开启功能,⾃动扫描
定义异步任务类并使⽤
@Component
标记组件被容器扫描
,
异步⽅法加上
@Async
@SpringBootApplication
@ServletComponentScan
@EnableScheduling
@EnableAsync
public class DemoProjectApplication {
public static void main(String[] args) {
SpringApplication.run(DemoProjectApplication.class, args);
}
}
Controller
@GetMapping("async")
public JsonData testAsync(){
long begin = System.currentTimeMillis();
asyncTask.task1();
asyncTask.task2();
asyncTask.task3();
Future<String> task4 = asyncTask.task4();
Future<String> task5 = asyncTask.task5();
for(;;){
if(task4.isDone() && task5.isDone()){
try {
String task4Result = task4.get();
System.out.println(task4Result);
String task5Result = task5.get();
System.out.println(task5Result);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}finally {
break;
}
}
}
long end = System.currentTimeMillis();
return JsonData.buildSuccess( end - begin);
}
@Component
@Async
public class AsyncTask {
public void task1(){
try {
Thread.sleep(4000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" task 1 ");
}
public void task2(){
try {
Thread.sleep(4000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" task 2 ");
}
public void task3(){
try {
Thread.sleep(4000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" task 3 ");
}
public Future<String> task4(){
try {
Thread.sleep(4000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" task 4 ");
return new AsyncResult<String>("task4");
}
public Future<String> task5(){
try {
Thread.sleep(4000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" task 5 ");
return new AsyncResult<String>("task5");
}
}
@Component
public class VideoOrderTask {
//每2秒执行一次
//@Scheduled(fixedDelay = 4000)
//@Scheduled(fixedRate = 4000)
//@Scheduled(cron = "*/2 * * * * *")
public void sum(){
//正常的是从数据库中查询
System.out.println(LocalDateTime.now() + " 当前交易额="+ Math.random());
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}