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

时间:2012-07-10 15:02:54

标签: java

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

3 个答案:

答案 0 :(得分:10)

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

答案 1 :(得分:9)

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

答案 2 :(得分: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();