You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
1.7 KiB
53 lines
1.7 KiB
package command;
|
|
|
|
import model.CrawlResult;
|
|
import exception.CrawlerException;
|
|
import view.CrawlerView;
|
|
|
|
import java.util.List;
|
|
|
|
public class RetryCommand implements Command {
|
|
private final Command originalCommand;
|
|
private final int maxRetries;
|
|
private final CrawlerView view;
|
|
|
|
public RetryCommand(Command originalCommand, int maxRetries, CrawlerView view) {
|
|
this.originalCommand = originalCommand;
|
|
this.maxRetries = maxRetries;
|
|
this.view = view;
|
|
}
|
|
|
|
@Override
|
|
public List<CrawlResult> execute() throws CrawlerException {
|
|
CrawlerException lastException = null;
|
|
|
|
for (int attempt = 1; attempt <= maxRetries; attempt++) {
|
|
try {
|
|
view.showMessage("执行命令: " + originalCommand.getName()
|
|
+ " (尝试 " + attempt + "/" + maxRetries + ")");
|
|
return originalCommand.execute();
|
|
} catch (CrawlerException e) {
|
|
lastException = e;
|
|
view.showError("命令执行失败: " + e.getMessage());
|
|
|
|
if (attempt < maxRetries) {
|
|
view.showMessage("等待重试...");
|
|
try {
|
|
Thread.sleep(1000 * attempt);
|
|
} catch (InterruptedException ie) {
|
|
Thread.currentThread().interrupt();
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
view.showError("命令执行失败,已达到最大重试次数 " + maxRetries);
|
|
throw lastException;
|
|
}
|
|
|
|
@Override
|
|
public String getName() {
|
|
return "Retry[" + originalCommand.getName() + "]";
|
|
}
|
|
}
|