I want to create a function that will be called after a certain time. In addition, this should be repeated after the same amount of time. For example, a function may be called every 60 seconds.
Using java.util.Timer.scheduleAtFixedRate() and java.util.TimerTask is a possible solution:
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
To repeatedly call a method, you need to use some form of streaming 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 a good idea to repeat function calls repeatedly.
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();