Java 退出 class 函数

Java Quit class function

我有问题。我创建了这个 class 用 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() 计划检查特定变量,如果程序失去与互联网的连接,该变量将设置为 true,但该函数还必须阻止代码继续 ping API。实际上我想做一些 return 退出整个 class 代码,所以我需要创建一个新的 class 实例来再次启动 API 流。

如何从 Runnable checkConnectionTask 中取消此 class 中的所有代码(实际上是破坏 class)?

基本上你需要 close/clean 启动 resources/running 线程和 运行 从一开始的逻辑,将启动逻辑包装到单独的方法并添加一个用于清理将有助于:

    private void start() {
        startAccountEventStreaming();
        setConnectionCheckScheduler();
    }

    private void shutdown() {
        // possibly more code to make sure resources closed gracefully
        webSocketClient.close();
        keepAliveUserDataStreamPool.shutdown();
        checkConnectionPool.shutdown();
    }

    private void restart() {
        shutdown();
        start();
    }

所以你只需在检查器中调用 restart:

        Runnable checkConnectionTask = () -> {
            if (!MainDriver.connected) {
                restart();
            }
        };