我有一个应用程序需要从服务器请求数据,有时作为一次性请求,有时它需要以固定速率轮询。
对于一次性请求,我只使用这样的线程:
public void request() {
Thread requestThread = new Thread(this);
requestThread.start();
}
这些没关系,它们执行然后就完成了。
但是,对于长轮询任务,我似乎永远不能一次只执行其中一个。
我想要的是以下方法:
public void longPoll() {
try {
pollingScheduledExecutor.scheduleAtFixedRate(this, 0, 3, TimeUnit.SECONDS);
} catch (Exception ignored) {
}
}
只能存在一次,但现在发生的情况是,当我从第一堂课调用它时,它会正常开始,但在第二个任务调用后它永远不会停止。
如何强制执行只有一个全局实例 this ScheduledExecutorService?
对于上下文,这是这些方法所在的类:
public abstract class AbstractCommunicationChannel implements Runnable {
static String SERVER_ADDRESS = "http://0.0.0.0";
private URL url;
private JSONObject requestObject;
private JSONObject responseObject;
private volatile ScheduledExecutorService pollingScheduledExecutor = Executors.newSingleThreadScheduledExecutor();
public void longPoll() {
try {
pollingScheduledExecutor.scheduleAtFixedRate(this, 0, 3, TimeUnit.SECONDS);
} catch (Exception ignored) {
}
}
public void request() {
Thread requestThread = new Thread(this);
requestThread.start();
}
AbstractCommunicationChannel(URL url, JSONObject requestObject) {
this.url = url;
this.requestObject = requestObject;
}
/**
* This is the general purpose tool for hitting the server and getting a response back.
*/
public void run() {
Log.i("requestObject", requestObject.toString());
try {
HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
}
}
冉冉说
相关分类