Attach Actions to Asynchronous Apex Jobs Using Transaction Finalizers (Pilot)

With Summer ’20, we enhance the Transaction Finalizers feature with a FinalizerContext.getRequestId() method, which returns the request ID of the Finalizer execution.

Where: This change applies to Lightning Experience and Salesforce Classic only in scratch orgs that have enabled the feature during org creation. Because finalizers are currently in pilot and are available only in scratch orgs, do not attempt to package finalizers.

Note

Note

The TransactionFinalizers feature is available as a pilot program only in scratch orgs that have enabled the feature during org creation. The functionality of this feature is subject to change, and is not available for production organizations while in pilot. Pilot programs are subject to change. This feature isn’t generally available unless or until Salesforce announces its general availability in documentation or in press releases or public statements. We can’t guarantee general availability within any particular time frame or at all. Make your purchase decisions only on the basis of generally available products and features. You can provide feedback and suggestions for this feature in the TransactionFinalizers group in the Trailblazer Community.

How:

The System.FinalizerContext interface contains four methods.
  • getAsyncApexJobId method: Returns the ID of the queueable job for which this finalizer is defined.
  • getRequestId method: Returns the request ID shared by both the finalizer execution and the Queueable job to which the finalizer is attached. This shared ID helps in filtering logs of a Queueable job and its attached finalizer.
  • getResult method: Returns the System.ParentJobResult enum, which represents the  result of the parent asynchronous Apex queueable job to which the finalizer is attached. The enum takes these values: SUCCESS, UNHANDLED_EXCEPTION.
  • getException method: Returns the exception with which the queueable job failed when getResult is UNHANDLED_EXCEPTION, null otherwise.
To attach actions to your queueable jobs, implement the FinalizerContext interface as follows.
  1. Define a class that implements the System.FinalizerContext interface.
  2. Attach a finalizer within a queueable job’s execute method. To attach the finalizer, invoke the System.attachFinalizer method, using as argument the instantiated class that implements the System.FinalizerContext interface.
Note

Note

Only one finalizer instance can be attached to any queueable job. You can enqueue a single asynchronous Apex job (queueable, future, or batch) in the finalizer’s implementation of the execute method. Callouts are allowed in finalizer implementations.

For more information on Transaction Finalizers, including examples, see Transaction Finalizers (Pilot) in Apex Developer Guide.