In your "Good" block, you need to actually consume a value from the queue, and you need to reset the wait
flag.
Below is a fully runnable example. The content of the queue doesn't matter, so I just let it contain the execution time (scheduled and actual). As an example, I didn't want to let it run forever, so the never-ending while
loop was changed to stop after 10 values. To show that multiple values added quickly enough would be processed without printing "Waiting", the timer will add 2 values about 33% of the time.
// Create queue, and task for adding values to queue
final ConcurrentLinkedQueue<Date[]> wait_list = new ConcurrentLinkedQueue<Date[]>();
TimerTask task = new TimerTask() {
@Override public void run() {
Date actualTime = new Date();
Date scheduledTime = new Date(this.scheduledExecutionTime());
wait_list.add(new Date[] { scheduledTime, actualTime });
if (actualTime.getTime() % 3 == 0) // Add two elements about 33% of the time
wait_list.add(new Date[] { scheduledTime, actualTime });
}
};
// Run task every 0.1 second
Timer timer = new Timer();
timer.scheduleAtFixedRate(task, 100, 100);
// Process next 10 values, printing "Waiting" whenever queue goes empty
SimpleDateFormat fmt = new SimpleDateFormat("mm:ss.SSS");
boolean waiting = false;
int countDown = 10;
while (countDown > 0) {
if (wait_list.isEmpty()) {
if (! waiting) {
System.out.println("Waiting");
waiting = true;
}
} else {
Date[] date = wait_list.remove();
System.out.println("Good: scheduled=" + fmt.format(date[0]) + ", actual=" + fmt.format(date[1]));
waiting = false;
countDown--;
}
}
// Stop timer
timer.cancel();
Output
Waiting
Good: scheduled=57:49.708, actual=57:49.718
Waiting
Good: scheduled=57:49.808, actual=57:49.811
Waiting
Good: scheduled=57:49.908, actual=57:49.920
Good: scheduled=57:49.908, actual=57:49.920
Waiting
Good: scheduled=57:50.008, actual=57:50.014
Waiting
Good: scheduled=57:50.108, actual=57:50.123
Waiting
Good: scheduled=57:50.208, actual=57:50.217
Good: scheduled=57:50.208, actual=57:50.217
Waiting
Good: scheduled=57:50.308, actual=57:50.310
Good: scheduled=57:50.308, actual=57:50.310