[英]How to run a number of task repeatedly and stop it after a certain amount of time in java
[英]How to repeatedly call a function after a certain amount of time
我想做一个将在一定时间后调用的函数。 同样,应在相同的时间后重复此操作。 例如,该函数可以每60秒调用一次。
使用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
为了重复调用方法,您需要使用在后台运行的某种形式的线程。 我建议使用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
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.