cancel
Showing results for 
Search instead for 
Did you mean: 

SAP CAP Java asynchronous event handlers

DC
Explorer
0 Kudos
954

Hi Team,

We wanting to allow users to trigger a long running job from a UI5 application with the custom action in CAP Java.

Once the user clicks on  a button, we call a custom action which in turn triggers (emit --> event) the LONG running job. But we want the response from the custom action straight away while the trigged job is now running in the background. The UI will refresh and update the stats that are in a DB in a setInterval loop  till all jobs are processed. 

Basically we need to start another and be able to return tot the UI. The emit event is synchronous hence we need some other solution.

Button --> call action in CAP JAVA application --> emit event to start a LONG process but return to UI while job is running backgroup.

I am struggling with "RequestContextRunner" and appreciate any help / guidance with this.

And also which phase i need to add this into so it becomes asynchronous.

@skymu89 

@marcbecker 

Thanks in advance.

 

 

 

View Entire Topic
marcbecker
Product and Topic Expert
Product and Topic Expert
0 Kudos

You will need to explicitly create a new thread in your action ON handler implementation, submit your long running task to the thread and finish the execution of the ON handler. The request will then return with a response, while the job is running in the background. You can use a standard Java ExecutorService for this. Make sure to think about the amount of parallel jobs you want to allow, etc. and configure that properly.

The RequestContextRunner can be used to propagate the original user and request context (e.g. tenant, user authentication, etc.) to the background job, if required.

The combined solution would look something like this (sketchy):

ExecutorService executor = Executors.newFixedThreadPool(10); // created once, shared

@On
public void myAction(MyActionContext context) {
  RequestContextRunner runner = runtime.requestContext();
  executor.submit(() -> {
    // optional: propagate request context
    runner.run(requestContext -> {
      // perform long running task here
    });
  });  
}

 

DC
Explorer
0 Kudos
Thanks Marc.