爬虫源获取分类增加超时逻辑

pull/1/head
Demo 4 years ago
parent 2970b9056a
commit 0ed92ad7ed
  1. 42
      app/src/main/java/com/github/tvbox/osc/viewmodel/SourceViewModel.java

@ -32,8 +32,13 @@ import org.json.JSONObject;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/** /**
* @author pj567 * @author pj567
@ -57,7 +62,7 @@ public class SourceViewModel extends ViewModel {
playResult = new MutableLiveData<>(); playResult = new MutableLiveData<>();
} }
public static final ExecutorService spThreadPool = Executors.newFixedThreadPool(3); public static final ExecutorService spThreadPool = Executors.newSingleThreadExecutor();
public void getSort(String sourceKey) { public void getSort(String sourceKey) {
if (sourceKey == null) { if (sourceKey == null) {
@ -67,13 +72,40 @@ public class SourceViewModel extends ViewModel {
SourceBean sourceBean = ApiConfig.get().getSource(sourceKey); SourceBean sourceBean = ApiConfig.get().getSource(sourceKey);
int type = sourceBean.getType(); int type = sourceBean.getType();
if (type == 3) { if (type == 3) {
spThreadPool.execute(new Runnable() { Runnable waitResponse = new Runnable() {
@Override @Override
public void run() { public void run() {
Spider sp = ApiConfig.get().getCSP(sourceBean); ExecutorService executor = Executors.newSingleThreadExecutor();
sortJson(sortResult, sp.homeContent(true)); Future<String> future = executor.submit(new Callable<String>() {
@Override
public String call() throws Exception {
Spider sp = ApiConfig.get().getCSP(sourceBean);
return sp.homeContent(true);
}
});
String sortJson = null;
try {
sortJson = future.get(15, TimeUnit.SECONDS);
} catch (TimeoutException e) {
e.printStackTrace();
future.cancel(true);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
} finally {
if (sortJson != null) {
sortJson(sortResult, sortJson);
} else {
sortResult.postValue(null);
}
try {
executor.shutdown();
} catch (Throwable th) {
th.printStackTrace();
}
}
} }
}); };
spThreadPool.execute(waitResponse);
} else if (type == 0 || type == 1) { } else if (type == 0 || type == 1) {
OkGo.<String>get(sourceBean.getApi()) OkGo.<String>get(sourceBean.getApi())
.tag(sourceBean.getKey() + "_sort") .tag(sourceBean.getKey() + "_sort")

Loading…
Cancel
Save