Temporal best practises to execute some cleanup activity before terminating workflow

Hi, I have a requirement to abort/terminate the workflow in some cases. Before terminating need to do cleanup like deleting whatever items got created during workflow execution. So just wanted to understand what is the best way to do cleanup activities?

I tried using signal method on workflow to do cleanup activity and triggered signal and terminating the workflow. But the issue is that as the signal method is asynchronous the workflow is getting terminated before signal processing gets completed. So to wait for the signal to complete wrote another query method where we have put the logic to wait for the flag to be marked true like
Workflow.await(()->flag) → flag gets set upon completion of signal method

@Vamsikrishna_Mandala

Can you send a cancellation request instead of terminating the workflow?

You can learn about the difference here:

So just wanted to understand what is the best way to do cleanup activities?

With cancellation, Inside the activity, you can handle ActivityCompletionException and do any additional cleanup https://github.com/temporalio/samples-java/blob/f107c79e29453ecd43dce522dfd1c980439b3762/core/src/main/java/io/temporal/samples/hello/HelloCancellationScope.java#L207

The same in your workflow code , you can handle the exception and create a detached scope to run an activity

Antonio