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();
  • 判断是否执行完
    • !a.isDone() :执行完了




原文地址:https://www.cnblogs.com/ziyue7575/p/32d7c3925e84470764784b1535646a37.html