Use java.util.TimerTask
java.util.Timer t = new java.util.Timer(); t.schedule(new TimerTask() { @Override public void run() { System.out.println("This will run every 5 seconds"); } }, 5000, 5000);
If you are using a graphical interface, you can use javax.swing.Timer , example:
int delay = 5000; //milliseconds ActionListener taskPerformer = new ActionListener() { public void actionPerformed(ActionEvent evt) { System.out.println("This will run every 5 seconds"); } }; new javax.swing.Timer(delay, taskPerformer).start();
Some information about the difference between java.util.Timer and java.swing.Timer : http://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html
Both and javax.swing.Timer provide the same basic functionality, but java.util.Timer is more general and has more features. javax.swing.Timer has two functions that can make it a bit easier to use with graphical interfaces. Firstly, its metaphor for event processing is familiar with the graphical interface of programmers and can deal with a dispatching event stream a bit easier. Secondly, automatic thread separation means that you do not have to take special steps to avoid spawning too many threads. Instead, your timer uses the same thread that is used to make the cursors blink, tool tips, etc.
source share