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.
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() .
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.
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
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
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With