我是一名 Java 初学者,正在寻找一种方法来执行以下操作:
- 从 csv 文件(csvreader)中一次读取一行。
- 对上一步中的数据进行一些处理。
- 如果花费的时间超过 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/