Java 计时器每 X 秒

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24894501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:25:04  来源:igfitidea点击:

Java Timer Every X Seconds

javatimerrepeat

提问by Grim Reaper

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); But that causes my whole game to stop working... If I try using a timer, for example:

所以,我基本上需要一个命令每 5 秒运行一次,但是 Timer 不起作用......我尝试了很多不同的方法,唯一有效的是 Thread.sleep(Milliseconds); 但这会导致我的整个游戏停止工作......如果我尝试使用计时器,例如:

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?

我怎样才能让这个计时器正确触发?

采纳答案by Isthatso

You should pair java.util.Timerwith 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 delaybefore 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()