我想制作一个在一定时间后调用的函数。此外,这应该在相同的时间后重复。例如,该函数可能每 60 秒调用一次。
问问题
13296 次
3 回答
10
使用java.util.Timer.scheduleAtFixedRate()
andjava.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
于 2012-07-10T15:04:19.287 回答
10
为了重复调用一个方法,您需要使用某种形式的在后台运行的线程。我建议使用ScheduledThreadPoolExecutor:
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
exec.scheduleAtFixedRate(new Runnable() {
public void run() {
// code to execute repeatedly
}
}, 0, 60, TimeUnit.SECONDS); // execute every 60 seconds
于 2012-07-10T15:15:46.853 回答
1
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();
于 2014-06-15T10:44:04.960 回答