How to repeatedly call a function after a certain time

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.

+4
source share
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 
+9
source

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 
+6
source

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(); 
0
source

All Articles