この文章は Salesforce 機械翻訳システムを使用して翻訳されました。詳細はこちらをご参照ください。
英語に切り替える

Transaction Finalizers

Transaction Finalizers 機能により、System.Finalizer インターフェースを使用して、キュー可能フレームワークを使う非同期 Apex ジョブにアクションを関連付けることができます。具体的な使用事例として、キュー可能ジョブが失敗した場合の回復アクションの設計が挙げられます。
Transaction Finalizers の機能により、非同期ジョブが成功または失敗したときに実行されるアクションを直接指定できます。Transaction Finalizers よりも前は、非同期ジョブの失敗に対して、次の 2 つのアクションしか取ることができませんでした。
  • SOQL クエリを使用して AsyncApexJob の状況をポーリングし、ジョブが失敗している場合にジョブを再度キューに追加する
  • Apex の一括処理メソッドで未対応の例外が発生した場合に、BatchApexErrorEvents を起動する
Transaction Finalizers を使用すると、後処理アクションシーケンスをキュー可能ジョブに関連付け、ジョブの実行結果に基づいて関連するアクションを実行できます。

未対応の例外が原因で失敗したキュー可能ジョブは、Transaction Finalizer によって連続して 5 回再度キューに追加できます。この制限は、キュー可能ジョブの一連の連続した失敗に適用されます。未対応の例外が発生せずにキュー可能ジョブが完了すると、カウンタはリセットされます。

Finalizers は内部クラスとして実装できます。また、同じクラスで Queueable インターフェースと Finalizer インターフェースの両方を実装できます。

System.Finalizer インターフェース

System.Finalizer インターフェースには execute メソッドがあります。
1global void execute(System.FinalizerContext ctx) {}
このメソッドは、指定した FinalizerContext インスタンスが関連付けられているキューに入れられたジョブごとにコールされます。execute メソッド内で、キュー可能ジョブの終了時に実行されるアクションを定義できます。System.FinalizerContext のインスタンスは、Apex ランタイムエンジンによって引数として execute メソッドに挿入されます。

System.FinalizerContext インターフェース

System.FinalizerContext インターフェースには 4 つのメソッドがあります。
  • getAsyncApexJobId メソッド
    1global Id getAsyncApexJobId {}
    この Finalizer が定義されているキュー可能ジョブの ID を返します。
  • getRequestId メソッド
    1global String getRequestId {}
    要求を一意に識別する文字列である要求 ID を返し、イベント監視ログと関連付けることができます。AsyncApexJob テーブルと関連付けるには、代わりに getAsyncApexJobId メソッドを使用します。キュー可能ジョブと Finalizer の実行の両方が (同じ) 要求 ID を使用します。
  • getResult メソッド
    1global System.ParentJobResult getResult {}
    Finalizer が関連付けられている親非同期 Apex キュー可能ジョブの結果を表す System.ParentJobResult 列挙を返します。この列挙は、SUCCESSUNHANDLED_EXCEPTION の値を取ります。
  • getException メソッド
    1global System.Exception getException {}
    getResultUNHANDLED_EXCEPTION の場合はキュー可能ジョブが失敗し、それ以外の場合は null になる例外を返します。
System.attachFinalizer メソッドを使用して Finalizer をキュー可能ジョブに関連付けます。
  1. System.Finalizer インターフェースを実装するクラスを定義します。
  2. キュー可能ジョブの execute メソッド内で Finalizer を関連付けます。Finalizer を関連付けるには、System.Finalizer インターフェースを実装するインスタンス化されたクラスの引数として System.attachFinalizer メソッド使用して、このメソッドを呼び出します。
    1global void attachFinalizer(Finalizer finalizer) {}

実装の詳細

  • 1 つの Finalizer インスタンスのみを任意のキュー可能ジョブに関連付けることができます。
  • execute メソッドの Finalizer の実装では、1 つの非同期 Apex ジョブ (キュー可能ジョブ、実行予定ジョブ、一括処理ジョブ) をキューに追加できます。
  • Finalizer の実装ではコールアウトを使用できます。
  • Finalizer フレームワークは、Finalizer オブジェクトが関連付けられている場合、キュー可能実行の終了時に Finalizer オブジェクトの状態を使用します。このため、Finalizer が関連付けられた後の状態の変更がサポートされます。

Finalizer のログ記録の例

次の例では、Transaction Finalizers を使用して、ジョブが成功したかどうかに関係なくキュー可能ジョブからメッセージをログ記録する方法を示します。この LoggingFinalizer クラスでは、Queueable インターフェースと Finalizer インターフェースの両方を実装します。キュー可能実装では、Finalizer がインスタンス化され、Finalizer が関連付けられた後、ログメッセージをバッファリングするための addLog() メソッドが呼び出されます。LoggingFinalizer の Finalizer 実装には、キュー可能ジョブからのメッセージを Fnalizer の状態にバッファリングできる addLog(message, source) メソッドが含まれます。キュー可能ジョブが完了すると、Finalizer インスタンスは、バッファリングされたログをコミットします。Finalizer の状態は、キュー可能ジョブが失敗しても保持され、Finalizer の実装または実行内の DML で使用できます。

1public class LoggingFinalizer implements Finalizer, Queueable {
2
3  // Queueable implementation
4  // A queueable job that uses LoggingFinalizer to buffer the log
5  // and commit upon exit, even if the queueable execution fails
6
7    public void execute(QueueableContext ctx) {
8        String jobId = '' + ctx.getJobId();
9        System.debug('Begin: executing queueable job: ' + jobId);
10        try {
11            // Create an instance of LoggingFinalizer and attach it
12            LoggingFinalizer f = new LoggingFinalizer();
13            System.attachFinalizer(f);
14
15            // While executing the job, log using LoggingFinalizer.addLog()
16            // Note that addlog() modifies the Finalizer's state after it is attached 
17            DateTime start = DateTime.now();
18            f.addLog('About to do some work...', jobId);
19
20            while (true) {
21              // Results in limit error
22            }
23        } catch (Exception e) {
24            System.debug('Error executing the job [' + jobId + ']: ' + e.getMessage());
25        } finally {
26            System.debug('Completed: execution of queueable job: ' + jobId);
27        }
28    }
29
30  // Finalizer implementation
31  // Logging finalizer provides a public method addLog(message,source) that allows buffering log lines from the Queueable job.
32  // When the Queueable job completes, regardless of success or failure, the LoggingFinalizer instance commits this buffered log.
33  // Custom object LogMessage__c has four custom fields-see addLog() method.
34
35    // internal log buffer
36    private List<LogMessage__c> logRecords = new List<LogMessage__c>();
37
38    public void execute(FinalizerContext ctx) {
39        String parentJobId = '' + ctx.getAsyncApexJobId();
40        System.debug('Begin: executing finalizer attached to queueable job: ' + parentJobId);
41
42        // Update the log records with the parent queueable job id
43        System.Debug('Updating job id on ' + logRecords.size() + ' log records');
44        for (LogMessage__c log : logRecords) {
45            log.Request__c = parentJobId; // or could be ctx.getRequestId()
46        }
47        // Commit the buffer
48        System.Debug('committing log records to database');
49        Database.insert(logRecords, false);
50
51        if (ctx.getResult() == ParentJobResult.SUCCESS) {
52            System.debug('Parent queueable job [' + parentJobId + '] completed successfully.');
53        } else {
54            System.debug('Parent queueable job [' + parentJobId + '] failed due to unhandled exception: ' + ctx.getException().getMessage());
55            System.debug('Enqueueing another instance of the queueable...');
56        }
57        System.debug('Completed: execution of finalizer attached to queueable job: ' + parentJobId);
58    }
59
60    public void addLog(String message, String source) {
61        // append the log message to the buffer
62        logRecords.add(new LogMessage__c(
63            DateTime__c = DateTime.now(),
64            Message__c = message,
65            Request__c = 'setbeforecommit',
66            Source__c = source
67        ));
68    }
69}

キュー可能ジョブの再試行の例

次の例では、Finalizer で失敗したキュー可能ジョブを再度キューに追加する方法を示します。また、キュー可能チェーニング制限の 5 回までジョブを再度キューに追加できることを示します。

1public class RetryLimitDemo implements Finalizer, Queueable {
2
3  // Queueable implementation
4  public void execute(QueueableContext ctx) {
5    String jobId = '' + ctx.getJobId();
6    System.debug('Begin: executing queueable job: ' + jobId);
7    try {
8        Finalizer finalizer = new RetryLimitDemo();
9        System.attachFinalizer(finalizer);
10        System.debug('Attached finalizer');
11        Integer accountNumber = 1;
12        while (true) { // results in limit error
13          Account a = new Account();
14          a.Name = 'Account-Number-' + accountNumber;
15          insert a;
16          accountNumber++;
17        }
18    } catch (Exception e) {
19        System.debug('Error executing the job [' + jobId + ']: ' + e.getMessage());
20    } finally {
21        System.debug('Completed: execution of queueable job: ' + jobId);
22    }
23  }
24
25  // Finalizer implementation
26  public void execute(FinalizerContext ctx) {
27    String parentJobId = '' + ctx.getAsyncApexJobId();
28    System.debug('Begin: executing finalizer attached to queueable job: ' + parentJobId);
29    if (ctx.getResult() == ParentJobResult.SUCCESS) {
30        System.debug('Parent queueable job [' + parentJobId + '] completed successfully.');
31    } else {
32        System.debug('Parent queueable job [' + parentJobId + '] failed due to unhandled exception: ' + ctx.getException().getMessage());
33        System.debug('Enqueueing another instance of the queueable...');
34        String newJobId = '' + System.enqueueJob(new RetryLimitDemo()); // This call fails after 5 times when it hits the chaining limit
35        System.debug('Enqueued new job: ' + newJobId);
36    }
37    System.debug('Completed: execution of finalizer attached to queueable job: ' + parentJobId);
38  }
39}

ベストプラクティス

ISV では、Finalizer をグローバルで使用している際に、パッケージで状態を変更するメソッドを使う場合には注意が必要です。登録者組織の実装から、グローバル Finalizer のこのようなメソッドを呼び出すと、予期しない動作が発生する可能性があります。状態を変更するメソッドすべて調べて、Finalizer の状態や全体の動作にどのような影響を与えるかを確認してください。