how to execute method c() if method b() has not been called for more than N seconds?

Viewed 40

method a() sends data to method b(), how to execute method c() if method b() has not been called for more than N seconds and repeat this cycle if method b() receives data again?

public void methodB(byte[] audioData) throws IOException {
            byte[] transcodedVoice = transcodeVoice(audioData);
            recognizer.acceptWaveForm(transcodedVoice, transcodedVoice.length);
    }

public void methodC() {
            //do Something
            System.out.println("Method B stops getting data")
    }
1 Answers

Debouncer class

public class Debouncer {
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
private final ConcurrentHashMap<Object, Future<?>> delayedMap = new ConcurrentHashMap<>();

/**
 * Debounces {@code callable} by {@code delay}, i.e., schedules it to be executed after {@code delay},
 * or cancels its execution if the method is called with the same key within the {@code delay} again.
 */
public void debounce(final Object key, final Runnable runnable, long delay, TimeUnit unit) {
    final Future<?> prev = delayedMap.put(key, scheduler.schedule(new Runnable() {
        @Override
        public void run() {
            try {
                runnable.run();
            } finally {
                delayedMap.remove(key);
            }
        }
    }, delay, unit));
    if (prev != null) {
        prev.cancel(true);
    }
}

public void shutdown() {
    scheduler.shutdownNow();
}
}

My class with method b()

final Debouncer debouncer = new Debouncer();
public void methodB(byte[] audioData) throws IOException {
        byte[] transcodedVoice = transcodeVoice(audioData);
        recognizer.acceptWaveForm(transcodedVoice, transcodedVoice.length);

        debouncer.debounce(Void.class, new Runnable() {
                @Override public void run() {
                    System.out.println("Method B stops getting data");
                }
            }, 300, TimeUnit.MILLISECONDS);
}
Related