java 如何在一定时间后重复调用函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11416242/
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-10-31 05:00:58  来源:igfitidea点击:

How to repeatedly call a function after a certain amount of time

java

提问by Fisol Rasel

I want to make a function that will be called after certain amount of time. Also, this should be repeated after the same amount of time. For example, the function may be called every 60 seconds.

我想制作一个在一定时间后调用的函数。此外,这应该在相同的时间后重复。例如,该函数可能每 60 秒调用一次。

回答by hmjd

Using java.util.Timer.scheduleAtFixedRate()and java.util.TimerTaskis a possible solution:

使用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

回答by Tudor

In order to call a method repeatedly you need to use some form of threading that runs in the background. I recommend using ScheduledThreadPoolExecutor:

为了重复调用一个方法,您需要使用某种形式的在后台运行的线程。我建议使用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

回答by Omkar

Swing Timer is also good idea to implement repeatedly function calls.

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();