繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM