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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With