Pregunta

I have a Java program that has a loop in it that checks for new messages every twenty seconds.

Example:

while (true) {
    Thread.sleep(20000);
    newMessages();
}

This works when the computer is being run. However, if the user would to put their computer to sleep and then wake it up some duration of time later, the whole program gets messed up and no longer checks for messages every twenty seconds. Is there a way to correct this?

¿Fue útil?

Solución

Instead of using Thread.sleep you can use Timer.

A facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals.

Your code might be:

final Timer timer = new Timer();
final TimerTask task = new TimerTask() {        
    @Override
    public void run() {
        newMessages();
    }
};      
timer.scheduleAtFixedRate(task, new Date(), 20000);

Timer Javadoc

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top