我想创建一个程序,如果他们在执行过程中检测到任何异常错误,就可以重新启动。
假设我的程序正在尝试读取文件。如果程序无法读取文件,那么它将具有FileNotFound异常。发生此异常后,程序本身将重新启动并再次重试。此过程将继续 3次,如果程序仍然无法读取该文件,则程序将终止并打印异常消息。
我创建了读取文件部分,但如果检测到错误,我将无法重新启动程序。任何帮助将不胜感激。我已经在重新启动方法中包含了我想要做的pesudo代码。
fileReader.java
private static final int MAX_RETRIES = 3 ;
private static final int WAIT_BETWEEN_RETRIES_SEC = 30 ;
public static void main(String... args)
{
int retry = 1;
while (retry <= MAX_RETRIES) {
try {
//this method is okay, good. pass to next method.
readFile();
//error detected, retry only this method. Error fixed, pass to next method
method2();
//error detected, retry only this method. Error fixed, pass to next method
method3();
method4();
method5();
break;
} catch (IOException e) {
e.printStackTrace();
retry++;
try {
Thread.sleep(WAIT_BETWEEN_RETRIES_SEC * 1000);
} catch (InterruptedException e1) {}
}
}
if (retry == MAX_RETRIES) {
System.out.println("Failed!");
return;
}
// success
}
private static void readFile() throws IOException {
//read file code
}
答案 0 :(得分:2)
而不是重新启动,你可以(并且应该)在main()中处理它。例如:
private static final int MAX_RETRIES = 3 ;
private static final int WAIT_BETWEEN_RETRIES_SEC = 30 ;
public static void main(String... args)
{
int retry = 1;
while (retry <= MAX_RETRIES) {
try {
readFile();
break;
} catch (IOException e) {
e.printStackTrace();
retry++;
try {
Thread.sleep(WAIT_BETWEEN_RETRIES_SEC * 1000);
} catch (InterruptedException e1) {}
}
}
if (retry == MAX_RETRIES) {
System.out.println("Failed!");
return;
}
// success
}
private static void readFile() throws IOException {
//read file code
}
答案 1 :(得分:0)
在不成功地读取文件后,您不必重新启动整个应用程序 - 只需重新运行有问题的函数(在这种情况下为readFile())。
只需将readFile()
放入reLaunch()
功能
private static void reLaunch(int relaunchAttempt){
readFile();
}
或者
private static void readFile(){
try{
//read file code
}catch(FileNotFoundException e){
//relaunch the application if error detected
readFile(count);
e.printStackTrace()
}
}
维持readFile()
功能
答案 2 :(得分:0)
请尝试在java.util.concurrent包下使用FutureTask。这支持您正在寻找的功能。
答案 3 :(得分:0)
public class fileReader {
private static final MAX_RETRY = 3;
public static void main (String[] args){
int retry = 0;
while (retry++ < MAX_RETRY) {
try {
readFile();
break; // Break while loop
} catch (Exception e) {
if (retry == MAX_RETRY) {
// Failed 3 times
return;
}
}
}
// Success!
method1();
method2();
method3();
}
private static void readFile(){ ... }
private static method1(){ ... }
private static method2(){ ... }
private static method3(){ ... }
}
答案 4 :(得分:0)
使用Failsafe:
RetryPolicy retryPolicy = new RetryPolicy()
.retryOn(IOException.class);
.withMaxRetries(MAX_RETRIES)
.withDelay(30, TimeUnit.SECONDS);
Failsafe.with(retryPolicy)
.onFailure(e -> System.out.println("Failed!"))
.run(() -> doStuff());
非常简单。
使用这种方法,Failsafe会为您重试,RetryPolicy可以灵活地指定何时应该执行重试以及是否在重试之间延迟。