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.
Asked
Active
Viewed 1.5k times
7
-
http://stackoverflow.com/a/11434143/3514144 – Ajay Pandya Aug 24 '15 at 05:40
3 Answers
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
-
good, although javax.swing.timer may be a better choice if Fisol Rasel is using lots of Swing components – the_underscore_key Jul 10 '12 at 15:20
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
-
@VNJ: No, the worker threads cannot exist if the parent process is killed. – Tudor Apr 27 '15 at 09:52
-
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