0

how to call method multiple times within given time java

Ex: if I want to call method A() for 3 times within 120 seconds. these two values should be configurable

chabha
  • 29
  • 8
  • 1
    Have a look at timers. Those should provide what you want. – Thomas Dec 09 '20 at 17:04
  • 1
    [ScheduledExecutorService](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledExecutorService.html) is what you need – Zinc Dec 09 '20 at 17:17

1 Answers1

0

You should take a look at Timers in Java. Documentation of Java SE 8 of Timer can be found here.

Here's an example: You can adjust the delay, period to your own preference.

// Initialize the Timer, this is the actual function that will start a TimerTask
private static final Timer timer = new Timer();

// Initialize the TimerTask, this is like the recipe for the Timer
private static final TimerTask task = new TimerTask() {
        // Create a variable to keep track how many times we have ran this code
        private int count = 0;

        // Function that will be ran in the TaskTimer
        public void run() {
            // Your Code goes here

            // Add to the amount of times we have ran this code
            count++;

            // If the count has reached 3...
            if( count == 3 ) {
                // we cancel the task
                task.cancel();
            }
        }
    };

    // Using the TimerTask
    public static void main( String[] args ) {
        // Set the delay (adjust this to your own needs)
        long delay = 2000;

        // Set the period (adjust this to your own needs)
        long period = 5000;

        // Schedule the TimerTask
        timer.schedule(task, delay, period);
    }

It's always a good idea to take a look if your dependency has it's own set of Timer and AsyncTimer, as sometimes it's more efficient to use there's.

Jason C
  • 1
  • 2