首页 > 解决方案 > 如果我得到响应,如何等待 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;
}

标签: javaspring-boot

解决方案


您可以使用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
}

但是,如果达到超时,这种方式将停止任务。我不确定这是否是你想要的。


推荐阅读