7

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.

Peter
  • 13,733
  • 11
  • 75
  • 122
Fisol Rasel
  • 359
  • 2
  • 5
  • 7

3 Answers3

10

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

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
hmjd
  • 120,187
  • 20
  • 207
  • 252
10

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 exec = new ScheduledThreadPoolExecutor(1);
exec.scheduleAtFixedRate(new Runnable() {
           public void run() {
                // code to execute repeatedly
           }
       }, 0, 60, TimeUnit.SECONDS); // execute every 60 seconds
Tudor
  • 61,523
  • 12
  • 102
  • 142
1

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

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(); 
Omkar
  • 1,108
  • 10
  • 19