Search code examples
javabinance

Java Quit class function


I have a problem. I created this class that opens a websocket stream with Binance:

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);
    }

}

Now the setConnectionCheckScheduler() schedules a check for a specific variable, which gets set to true if the program lost connection to the internet, but the function also has to stop the code from continuing with pinging the API. Actually I want to do some kind of return which quits the entire class code, so I need to create a new instance of the class to start the API stream again.

How can I cancel all the code (actually destroy the class) in this class from within the Runnable checkConnectionTask?


Solution

  • Basically you need to close/clean up the resources/running threads and run the logic from the beginning, wrapping start logic to separate method and add one for clean up will help:

        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();
        }
    

    so you just call restart in your checker:

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