gpt4 book ai didi

java - 做某事,如果花费的时间超过 x 秒,则继续下一个任务

转载 作者:行者123 更新时间:2023-11-30 10:50:31 37 4
gpt4 key购买 nike

我是一名 Java 初学者,正在寻找一种方法来执行以下操作:

  1. 一次读取一个 csv 文件 (csvreader)。
  2. 对上一步的数据做一些处理。
  3. 如果花费的时间超过 30 秒,则跳过该过程并继续下一行。

我在执行第 3 步时遇到问题。我需要为此设置计时器吗?我需要玩 try and catch 吗?你有什么建议?

这是我的代码简介:

public static void main(String[] args) throws IOException, InterruptedException{

CsvReader data = new CsvReader("data.csv");
data.readHeaders();

int index = 1;
int index_max = 50;
int retry = 0;
int retry_max = 2;

while (index < index_max)
{
if (retry == 0)
{ data.readRecord();

String Column1 = data.get("COLUMN1");
String Column2 = data.get("COLUMN3");
String Column3 = data.get("COLUMN4");
...
}
else
{
//Retry with the same data
}

try {
//Invoke webservice to send the data and write on DB after validation

if (positive.answer == 0)
{
System.out.println("Great!!!");
index++;
retry = 0;
}
else
{
System.out.println("Bummer");
index++;
retry = 0;
}
}
catch (Exception e) {
if (e instanceof webservice_Exception){
//The Exception is about the webservice, print it
index++;
retry = 0;
} else {
//The Exception is about another thing, could be a transmission issue, please retry
retry++;
if (retry == retry_max)
{
retry = 0;
index++;
}
}
}
}
data.close();
}

最佳答案

有些工具可以帮助您做您想做的事。

想到的是 Guava与其 TimeLimiter API。

使用方法如下:

    TimeLimiter timeLimiter = SimpleTimeLimiter.create(Executors.newSingleThreadExecutor());

MyData data = ... ;

// With Java 8
MyResult result = timeLimiter.callWithTimeout(() -> processData(data), 30, TimeUnit.SECONDS, true);

// Without Java 8
MyResult result = timeLimiter.callWithTimeout(new Callable<MyResult>() {
@Override public MyResult call() {
return processData(data);
}
}, 30, TimeUnit.SECONDS, true);

private MyResult processData(MyData data) {
...
return new MyResult();
}

关于java - 做某事,如果花费的时间超过 x 秒,则继续下一个任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35051785/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com