Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 816
Fisol Rasel Avatar asked Jul 10 '12 15:07

Fisol Rasel


People also ask

Which function used to call function repeatedly after specific time interval?

The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval() .

How do you call a function more than one time?

In order to run a function multiple times after a fixed amount of time, we are using few functions. setInterval() Method: This method calls a function at specified intervals(in ms). This method will call continuously the function until clearInterval() is run, or the window is closed.


3 Answers

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
like image 194
hmjd Avatar answered Sep 20 '22 13:09

hmjd


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
like image 34
Tudor Avatar answered Sep 21 '22 13:09

Tudor


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(); 
like image 21
Omkar Avatar answered Sep 19 '22 13:09

Omkar