Is there any way of creating a loop that would do the task every 3 secs without using a sleep function
For eg:
try {
while (true) {
System.out.println(new Date());
Thread.sleep(5 * 1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
But the problem while using sleep function is that, it just freezes the program.
The main idea of this loop is to get a sync with mysql database
(online).
解决方案
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 GUI, you can use the 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 info about the difference between java.util.Timer and java.swing.Timer:
http://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html
Both it and javax.swing.Timer provide the same basic functionality,
but java.util.Timer is more general and has more features. The
javax.swing.Timer has two features that can make it a little easier to
use with GUIs. First, its event handling metaphor is familiar to GUI
programmers and can make dealing with the event-dispatching thread a
bit simpler. Second, its automatic thread sharing means that you don't
have to take special steps to avoid spawning too many threads.
Instead, your timer uses the same thread used to make cursors blink,
tool tips appear, and so on.