gpt4 book ai didi

java - 如何在 java 中以周期性间隔执行操作?

转载 作者:搜寻专家 更新时间:2023-10-31 08:20:14 25 4
gpt4 key购买 nike

有没有办法创建一个循环,每 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.Timerjava.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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com