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\$

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.