【发布时间】:2021-11-04 04:11:57
【问题描述】:
我有问题。我创建了这个类,它使用 Binance 打开一个 websocket 流:
public class AccountStream extends Driver {
private Integer agentId;
private String API_KEY;
private String SECRET;
private String listenKey;
private Order newOrder;
private String LOG_FILE_PATH;
public AccountStream(Integer agentId) {
this.agentId = agentId;
// Load binance config
HashMap<String, String> binanceConfig = MainDriver.getBinanceConfig(agentId);
API_KEY = binanceConfig.get("api_key");
SECRET = binanceConfig.get("secret");
startAccountEventStreaming();
setConnectionCheckScheduler();
}
private void startAccountEventStreaming() {
BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(API_KEY, SECRET);
BinanceApiRestClient client = factory.newRestClient();
// First, we obtain a listenKey which is required to interact with the user data stream
listenKey = client.startUserDataStream();
// Then, we open a new web socket client, and provide a callback that is called on every update
BinanceApiWebSocketClient webSocketClient = factory.newWebSocketClient();
// Listen for changes in the account
webSocketClient.onUserDataUpdateEvent(listenKey, response -> {
System.out.println(response);
});
// Ping the datastream every 30 minutes to prevent a timeout
ScheduledExecutorService keepAliveUserDataStreamPool = Executors.newScheduledThreadPool(1);
Runnable pingUserDataStream = () -> {
client.keepAliveUserDataStream(listenKey);
};
keepAliveUserDataStreamPool.scheduleWithFixedDelay(pingUserDataStream, 0, 30, TimeUnit.MINUTES);
}
private void setConnectionCheckScheduler() {
ScheduledExecutorService checkConnectionPool = Executors.newScheduledThreadPool(1);
Runnable checkConnectionTask = () -> {
if (!MainDriver.connected) {
// DESTORY ENTIRE CLASS HERE
}
};
checkConnectionPool.scheduleWithFixedDelay(checkConnectionTask, 0, 1, TimeUnit.SECONDS);
}
}
现在setConnectionCheckScheduler() 安排检查特定变量,如果程序失去与 Internet 的连接,该变量将设置为 true,但该函数还必须阻止代码继续 ping API。实际上我想做某种return 来退出整个类代码,所以我需要创建一个新的类实例来再次启动 API 流。
如何从Runnable checkConnectionTask 中取消该类中的所有代码(实际上是销毁该类)?
【问题讨论】:
-
是的,我认为 API 流在没有互联网后会自行关闭,因为它没有收到任何更新。但是,是的,该类不再允许执行任何代码行