Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time elapsed since last data event

I have a class (shown below) which receives data updates. My aim is to find out if no data updates have been received 5 minutes since the last data update.

This is my code:

public class DataListener {

    private final ScheduledThreadPoolExecutor executor;
    private ScheduledFuture<Void> future;

    public DataUpdateListener() {
        executor = new ScheduledThreadPoolExecutor(1);
    }

    /**
     * Start listening for data.
     */
    public void start() {
        // do some setup...

        rescheduleTask();
    }

    /**
     * Called whenever a data event is received.
     */
    public void onEvent(final DataEvent event) {
        System.out.println("Received event: " + event);
        rescheduleTask();
    }

    private synchronized void rescheduleTask() {
        // cancel the existing task
        if (future != null) {
            future.cancel(true);
            executor.purge();
        }

        // schedule a new one
        future = executor.schedule(new Callable<Void>() {
            @Override
            public Void call() {
                System.out.println("No data events received in the last 5 minutes!");
                // do some stuff...
                shutdown();
                return null;
            }
        }, 5, TimeUnit.MINUTES);
    }

    void shutdown() {
        executor.shutdownNow();
    }    
}

The class maintains a ScheduledThreadPoolExecutor. Whenever a data update is received, it cancels the existing task and schedules a new one.

I'm wondering if this approach is ok or if there is a better way to do this.

like image 758
dogbane Avatar asked Dec 07 '25 13:12

dogbane


1 Answers

Have you considered a priority queue implementation? If I have not misunderstood your problem, something like a PriorityBlockingQueue could be useful in this case. In particular you could check the poll() method with a desired timeout value.

like image 184
posdef Avatar answered Dec 10 '25 03:12

posdef