How to trigger activity before processing workflow request to cancel?


In my use case, I trigger an activity to publish metrics to biq query in a finally block. However, if the workflow gets canceled, that activity is never executed or can’t be because the workflow has been canceled and will get a failed CanceledFailed ActivityFailure.

I was wondering if there is a mechanism for a workflow to trigger the activity before fully processing the cancel request. For example, add some sort of listener?


You can use detached cancellation scope.

Here is sample in the Java SDK samples repo.

(Just thinkin out loud). For any clean up for a workflow, shouldn’t we just always run as a detached job?

  CancellationScope detached =
            Workflow.newDetachedCancellationScope(() -> greeting = activities.sayGoodBye(name));;

vs. catching an exception and then handling it?

  } catch (ActivityFailure af) {
        // Create a CancellationScope that is not linked to a parent scope
        // This can be used in the "cleanup" code after the Workflow Execution has been cancelled.
        CancellationScope detached =
            Workflow.newDetachedCancellationScope(() -> greeting = activities.sayGoodBye(name));;
        throw af;

Is there any downside with this? Also if it’s not attached to the parent scope, is it still show up in the workflow history?

I’m not sure I understand the question. The cleanup code has to run in a detached scope as it overwise would not be able to run anything as the surrounding scope can be canceled.

The reason try-catch is used is because any operation that is invoked from the canceled scope throws a cancelation failure. So catch is needed to perform cleanup in this case.

I was able to get a better understanding after reading this thread Can a child workflow/activity be triggered from a Workflow CancellationScope in the exception block? - #11 by anjo @tihomir shared with me. Thanks.

1 Like