I was wondering if there is a way to execute a function
after 15 seconds of another function executed in java asynchronously
. For eg I have 2 functions.
1. public void func1() {
}
2. public void func2() {
}
After func1
is executed, after 15 seconds i want func2
to be executed.
Justification - Func1
does an update
to an external interface
. External interface
takes approx 15 seconds time to process the data and store it. After 15 seconds I want to fetch certain processed data(URL)
from the interface
and store it in database
. I dont want the user to wait for the complete request to be completed. Please advise
CodePudding user response:
Have both calls in a method that you call asynchronously, and then in that method call the first one, then do a Thread.sleep(15000) before calling the second one.
CodePudding user response:
From the place you call func1()
, spawn a thread that will sleep for 15 sec and then call func2()
. Below is demo where main()
method calls func1()
then asynchronously calls func2
. That thrad takes care of waiting for 15 seconds, not main
method. main
method is unblocked immediately.
import java.util.Date;
public class AsyncCall {
public static void main(String[] args) {
AsyncCall solution = new AsyncCall();
solution.func1();
//async call
new Thread(() -> {
try {
Thread.sleep(15 * 1000);
solution.func2("async call");
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
//sync call : no need to call this but just for demo
solution.func2("sync call");
}
public void func1() {
System.out.println(new Date() " : func1 called");
}
public void func2(String arg) {
System.out.println(new Date() " : func2 called with arg: " arg);
}
}
Result:
Wed Mar 30 13:15:52 EDT 2022 : func1 called
Wed Mar 30 13:15:52 EDT 2022 : func2 called with arg: sync call
Wed Mar 30 13:16:07 EDT 2022 : func2 called with arg: async call
CodePudding user response:
Simplest solution would be to include Thread.sleep
between subsequent calls. But it will lead to a lot of threads in WAIT state and eventually clog up the system(thread pool) if the number of requests are too large.
Slightly better solution is to save the intermediate state in DB, and let cron job pick up these tasks in a batch and call func2. This is not so optimal solution for you since you're looking for something to be called in 15 secs. If you are okay with 10-15 mins of wait time, you can use this.
A more superior way is to have a callback that can help you know whether data has been processed or not as explained below.
Lets say Func1 is calling service A from Service X. Now Service A is doing the processing (lets say the processing is taking 10 secs), now service A will trigger a callback to Service X telling that the processing has been completed, and service X can call Service B.