2
\$\begingroup\$

I have implemented a method which will send one data to the server if it (Raspberry Pi Pin Input HIGH, in this case) occurs within 10 seconds. If this doesn't happen within 10 seconds then I should send some other data.

This implementation works for me, but I think that there should be another better implementation.

ScheduledExecutorService timeoutScheduler = Executors.newScheduledThreadPool(1);

ScheduledFuture<?> timeoutHandler = timeoutScheduler.schedule(() -> {
    try {
        socketConnection.writeData("String that should be sent if time is out");
        turnstileClosed.removeAllListeners();
        timeoutScheduler.shutdownNow();
    } catch (IOException e) {
        e.printStackTrace();
    }
}, 10_000, TimeUnit.MILLISECONDS);

turnstileClosed.addListener((GpioPinListenerDigital) event -> {
    try {
        if (event.getState() == PinState.HIGH) {
            socketConnection.writeData("String that should be sent within 10 seconds");
            timeoutHandler.cancel(true);
            timeoutScheduler.shutdownNow();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
});

timeoutScheduler.awaitTermination(10_000, TimeUnit.MILLISECONDS);
turnstileClosed.removeAllListeners();
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.