目录
异步任务
1.创建一个异步任务
public void hello() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在处理");
}
2.调用任务
@RequestMapping("/hello")
public String hello() {
asyncService.hello();//停止3秒
return "Ok";
}
3.开启异步任务注解——(无等待)
@Async
public void hello() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在处理");
}
定时任务
引入:
taskExecutor 任务执行者
taskScheduler 任务调度者
@EnableScheduling //开启定时注解功能
@Scheduled //什么时候之行
1.了解定时任务的语法
@Scheduled(cron = "* * * * * *")
在一个特点的时间执行这个方法 ~ Timer
上图(cron = "* * * * * *")代表的含义为:
秒,分,时,日,月,周几~
@Scheduled(cron = "0 * * * * ?")
public void hello() {
System.out.println("hello,你被执行了");
}
2.定时任务举例
//每分钟的第一1秒执行一次
@Scheduled(cron = "1 * * * * ?")
public void hello() {
System.out.println("hello,你被执行了");
}
//每隔1秒执行一次
@Scheduled(cron = "0/1 * * * * ?")
public void hello() {
System.out.println("hello,你被执行了");
}
//每天10点15分30 执行一次
@Scheduled(cron = "30 15 10 * * ? ")
public void hello() {
System.out.println("hello,你被执行了");
}
//每天10点18点30秒,每隔5分钟执行一次
@Scheduled(cron = "30 0/5 10,18 * * ?")
public void hello() {
System.out.println("hello,你被执行了");
}
总结
- 定时任务,可以帮助我们做一些脚本,例如抢票——(合法)
- 定时任务,方便我们做一些计划,更准确
- 异步任务,使得我们的代码更快捷的运行