springboot异步执行
springboot异步执行
1.使用场景
◆发送短信
◆发送邮件
◆App消息推送
◆节省运维凌晨发布任务时间提供效率
2.使用
(1)配置
- 注解:
- 主类:@EnableAsync//开启异步调用方法
- 任务类:
- 类注解:@Component//注入springboot
- 方法注解:@Async
@Component
public class AsyncTask {
@Async
public Future<Boolean> doTask11() throws Exception {//Future用来判断代码是否完成
long start = System.currentTimeMillis();
Thread.sleep(1000);
long end = System.currentTimeMillis();
System.out.println("任务1耗时:" + (end - start) + "毫秒");
return new AsyncResult<>(true);
}
}
//调用:
@Autowired
private AsyncTask asyncTask;
Future<Boolean> c = asyncTask.doTask33();1
2
public class AsyncTask {3
4
5
public Future<Boolean> doTask11() throws Exception {//Future用来判断代码是否完成6
long start = System.currentTimeMillis();7
Thread.sleep(1000);8
long end = System.currentTimeMillis();9
System.out.println("任务1耗时:" + (end - start) + "毫秒");10
return new AsyncResult<>(true);11
}12
}13
14
//调用:15
16
private AsyncTask asyncTask;17
Future<Boolean> c = asyncTask.doTask33();- 判断是否执行完
- !a.isDone() :执行完了

浙公网安备 33010602011771号