Java 中限制方法的返回时间最新方法

来自:网络
时间:2023-05-17
阅读:

最近在研究 ChatGPT 的 API 调用。

因为 ChatGPT 的 API 调用时间通常超过 30 秒。

所以我们希望在程序中限制这个方法的执行时间,不要让方法花太长时间去执行了。

JDK 方法

可以使用 JDK 中的 ExecutorService 方法来对调用的方法进行处理。

代码如下:

        ExecutorService executor = newCachedThreadPool();
        Callable<Object> task = new Callable<Object>() {
            public String call() {
                return callChatGPT(content);
            }
        };
        Future<Object> future = executor.submit(task);
        try {
            Object result = future.get(15, TimeUnit.SECONDS);
            contentGPT = (String) result;
        } catch (TimeoutException ex) {
            contentGPT = "ChatGPT API Time out, Please Re-try it";
        } catch (InterruptedException e) {
            contentGPT = "ChatGPT API Time out, Please Re-try it";
        } catch (ExecutionException e) {
            contentGPT = "ChatGPT API Time out, Please Re-try it";
        } finally {
            future.cancel(true); // may or may not desire this
        }

在我们的调用方法 callChatGPT 中,我们配置了一个 ExecutorService 执行器。

在这个执行器中,我们配置一个任务。

然后这个任务我们指定了执行时间为 15 秒。

如果这个方法的执行时间超过了 15 秒,程序将会抛出一个异常。

Java 中限制方法的返回时间最新方法

可以通过这个方法来限制方法的执行时间。

返回顶部
顶部