Java 如何在一定时间后重复调用函数
我想做一个函数,它将在一定时间后被调用。同样,这应该在相同的时间后重复。例如,该函数可以每60秒调用一次。使用Java 如何在一定时间后重复调用函数,java,Java,我想做一个函数,它将在一定时间后被调用。同样,这应该在相同的时间后重复。例如,该函数可以每60秒调用一次。使用java.util.Timer.scheduleAtFixedRate()和java.util.TimerTask是一种可能的解决方案: Timer t = new Timer(); t.scheduleAtFixedRate( new TimerTask() { public void run() { Syste
java.util.Timer.scheduleAtFixedRate()
和java.util.TimerTask
是一种可能的解决方案:
Timer t = new Timer();
t.scheduleAtFixedRate(
new TimerTask()
{
public void run()
{
System.out.println("hello");
}
},
0, // run first occurrence immediatetly
2000)); // run every two seconds
为了重复调用一个方法,您需要使用在后台运行的某种形式的线程。我建议使用:
Swing Timer还可以反复实现函数调用
Timer t = new Timer(0, null);
t.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//do something
}
});
t.setRepeats(true);
t.setDelay(1000); //1 sec
t.start();
很好,不过如果Fisol Rasel使用大量swing,javax.swing.timer可能是更好的选择components@VNJ:否,如果父进程被终止,工作线程将不存在。那么如何实现这一点?
Timer t = new Timer(0, null);
t.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//do something
}
});
t.setRepeats(true);
t.setDelay(1000); //1 sec
t.start();