- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
有没有办法创建一个循环,每 3 秒执行一次任务,而无需使用 sleep 功能
例如:
try {
while (true) {
System.out.println(new Date());
Thread.sleep(5 * 1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
但是使用 sleep 函数的问题是,它只是卡住了程序。
The main idea of this loop is to get a sync with mysql database (online).
最佳答案
使用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);
如果您使用的是 GUI,则可以使用 javax.swing.Timer
,示例:
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();
关于 java.util.Timer
和 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.
关于java - 如何在 java 中以周期性间隔执行操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17397259/
我是一名优秀的程序员,十分优秀!