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);