Home > Back-end >  How to delay asynchronously when a method is called consecutively?
How to delay asynchronously when a method is called consecutively?

Time:01-05

I want to have a delay of 1 minute before the printFirst() method is called without affecting the main thread.

Code

System.out.println(ts()   " Zero");
printFirst();
printFirst();
printFirst();
System.out.println(ts()   " Second");
System.out.println(ts()   " Third");
System.out.println(ts()   " Fourth");

I tried

static void printFirst() {
  new java.util.Timer().schedule(
    new java.util.TimerTask() {
      public void run() {
        System.out.println(ts()   " First");
      }
    },60000
  );
}

Actual Output

but the output was

Timestamp: 2023-01-05 17:40:43.664 Zero
Timestamp: 2023-01-05 17:40:43.666 Second
Timestamp: 2023-01-05 17:40:43.667 Third
Timestamp: 2023-01-05 17:40:43.667 Fourth
Timestamp: 2023-01-05 17:41:13.681 First
Timestamp: 2023-01-05 17:41:13.681 First
Timestamp: 2023-01-05 17:41:13.681 First

Expected

I was expecting an interval of 1 min between the 3 lines ending with "First".

Timestamp: 2023-01-05 17:40:43.664 Zero
Timestamp: 2023-01-05 17:40:43.666 Second
Timestamp: 2023-01-05 17:40:43.667 Third
Timestamp: 2023-01-05 17:40:43.667 Fourth
Timestamp: 2023-01-05 17:41:43.667 First
Timestamp: 2023-01-05 17:42:43.667 First
Timestamp: 2023-01-05 17:43:43.667 First

CodePudding user response:

While calling function, you can set the number of seconds as a parameter

System.out.println(ts()   " Zero");
printFirst(60000);
printFirst(12000);
printFirst(18000);
System.out.println(ts()   " Second");
System.out.println(ts()   " Third");
System.out.println(ts()   " Fourth");

In your function,

static void printFirst(long time) {
  new java.util.Timer().schedule(
    new java.util.TimerTask() {
      public void run() {
        System.out.println(ts()   " First");
      }
    },time
  );
}

CodePudding user response:

As an option you can set up your timer for periodic execution and limit the number of runs

static void printFirst(long delay, int numberOfIterations) {
    new java.util.Timer().schedule(
        new java.util.TimerTask() {
            private int counter = 0;
            public void run() {
                System.out.println(ts()   " First");

                if(  counter == numberOfIterations) {
                    this.cancel();
                }
            }
        }, delay, delay
    );
}

And then just run it with one command printFirst(60000, 3);

  • Related