我有一个特定的函数,希望在5秒后执行。如何在Java中实现这个功能?
我找到了javax.swing.timer,但是我无法理解如何使用它。看起来我正在寻找比这个类提供的更简单的东西。
请添加一个简单的使用示例。
我认为在这种情况下:
import javax.swing.*;
import java.awt.event.ActionListener;
is the best. 当问题是防止Ui堆栈或在重负载工作或网络调用之前看不到进度时,我们可以使用以下方法(根据我的经验):
延迟一秒后运行一个方法:
public static void startMethodAfterOneSeconds(Runnable runnable) {
Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
runnable.run();
}
});
timer.setRepeats(false); // Only execute once
timer.start();
}
延迟n秒后只运行一次的方法,不重复:
public static void startMethodAfterNMilliseconds(Runnable runnable, int milliSeconds) {
Timer timer = new Timer(milliSeconds, new ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
runnable.run();
}
});
timer.setRepeats(false); // Only execute once
timer.start();
}
延迟n秒后运行一个方法,并重复执行:
public static void repeatMethodAfterNMilliseconds(Runnable runnable, int milliSeconds) {
Timer timer = new Timer(milliSeconds, new ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
runnable.run();
}
});
timer.setRepeats(true); // Only execute once
timer.start();
}
使用方法:
startMethodAfterNMilliseconds(new Runnable() {
@Override
public void run() {
// myMethod(); // Your method goes here.
}
}, 1000);
new Handler().postDelayed(this::function, 1000);
或者你可以在内部实现该函数,例如:
new Handler().postDelayed(() -> System.out.println("A second later"), 1000);
第一个参数是函数,第二个参数是延迟时间(以毫秒为单位)。 在第一个示例中,被调用的函数名称为“function”。