[英]Java Timer Every X Seconds
So, I basically need a command to run every 5 seconds, but the Timer doesn't work... I tried so many different methods, The only thing that works is the Thread.sleep(Milliseconds); 所以,我基本上需要一个命令每5秒运行一次,但是Timer不起作用......我尝试了很多不同的方法,唯一有用的是Thread.sleep(Milliseconds); But that causes my whole game to stop working... If I try using a timer, for example: 但这导致我的整个游戏停止工作...如果我尝试使用计时器,例如:
Timer timer = new Timer(1000, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Hey");
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
How can I get this timer to fire correctly? 如何让这个计时器正确启动?
You should pair java.util.Timer
with java.util.TimerTask
您应该将java.util.Timer
与java.util.TimerTask
配对
Timer t = new Timer( );
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
System.out.println("Hey");
}
}, 1000,5000);
1000 means 1 second delay
before get executed & 5000 means will be repeated every 5 seconds
. 1000表示执行前1 second delay
,5000表示repeated every 5 seconds
。
To stop it , simply call t.cancel()
要停止它,只需调用t.cancel()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.