Search code examples
cadence-workflowtemporal-workflow

How to cancel activity that is invoked asynchronously from the Workflow?


We want to invoke a long-running activity asynchronously and after sometime based on the external signal, would like to cancel that long-running activity.

Async.procedure(activities::longRunningActivity)
// Execute some synchronous activities
Workflow.await(() -> !messageQueue.isEmpty());
if (messageQueue.remove(0) == "something") {
    // Cancel longRunningActivity
}

Currently the only way for an activity to learn about cancellation is through heartbeating. Make sure that your activity heartbeats and doesn't swallow the exception the heartbeat method throws.


Solution

  • Use CancellationScope:

      CancellationScope longRunningCancellationScope =
              Workflow.newCancellationScope(
                      () -> Async.procedure(activities::longRunningActivity));
      longRunningCancellationScope.run();
      // Execute some synchronous activities
      Workflow.await(() -> !messageQueue.isEmpty());
      if (messageQueue.remove(0) == "something") {
          longRunningCancellationScope.cancel();
      }