我有一个接收数据更新的类(如下所示)。我的目标是找出自上次数据更新后 5 分钟内是否没有收到任何数据更新。
这是我的代码:
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();
}
}
该类维护一个ScheduledThreadPoolExecutor
. 每当收到数据更新时,它都会取消现有任务并安排新任务。
我想知道这种方法是否可行,或者是否有更好的方法来做到这一点。