java - 如果我得到响应,如何等待 30 秒或完成?
问题描述
我有一个下面的方法,它发出一个通知,然后等待 30 秒。但是我想要实现的是发送一个通知,然后每秒检查一次数据库(太多了吗?),看看我是否得到了通知的响应。如果我收到通知的回复,那么我不需要再等待,我需要继续。否则我需要等到 30 秒。
@RequestMapping("/sendNotification")
public HashMap<String, Object> sendNotification(@RequestBody SingleFieldPojo singleFieldPojo) {
MessagingFCM.sendMessageToDevice("Title", singleFieldPojo.getToken());
final CountDownLatch latch = new CountDownLatch(1);
try {
latch.await(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
latch.countDown();
}
latch.countDown();
HashMap<String, Object> output = new HashMap<>();
output.put("success", jobStatusRepo.findById(singleFieldPojo.getJobBoardId()));
return output;
}
解决方案
您可以使用CompletableFuture
.
try {
thing = CompletableFuture.runAsync(myTask).get(10, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
} catch (TimeoutException | CancellationException e) {
// it timed out or was cancelled
}
但是,如果达到超时,这种方式将停止任务。我不确定这是否是你想要的。
推荐阅读
- sql - 这个公式可以添加到 WHERE 子句中吗?
- java - 如何在 Eclipse 和/或 STS IDE 中启用自动重建 Spring Boot 项目
- python - 在 Python 中装饰方法期间传递“self”参数
- vue.js - 如何将道具传递给命名视图
在 Vue.js 中? - python - Python - 如何删除不平衡的括号和引号
- r - 比较点模式,每个模式都有不同的窗口
- python - “源字符换行符”是什么意思?
- c++ - 纹理图像未正确映射
- mysql - Laravel Eloquent 模型按局部列和关系模型列值排序
- java - hibernate为不带括号的数组生成代码