Newer Version Available

This content describes an older version of this product. View Latest

Detecting Duplicate Queueable Jobs

Reduce resource contention and race conditions by enqueuing only a single instance of your async Queueable job based on the signature. Attempting to add more than one Queueable job to the processing queue with the same signature results in a DuplicateMessageException when you try to enqueue subsequent jobs.

Implementation Details

Build a unique queueable signature using the QueueableDuplicateSignature.Builder class. Add different strings, IDs, or integers using these methods from QueueableDuplicateSignature.Builder.

  • addString(inputString)
  • addId(inputId)
  • addInteger(inputInteger)

When the signature has the required components, call the .build() method and store the unique queueable job signature in the DuplicateSignature property in the AsyncOptions class. Enqueue your job by using the System.enqueueJob() method with the AsyncOptions parameter.

To determine the size, remaining size, and maximum size of the queueable job signature in bytes, use these methods from the QueueableDuplicateSignature.Builder class.

  • getSize()
  • getRemainingSize()
  • getMaxSize()

Examples

This example builds the async job signature with UserId and the string MyQueueable.

1AsyncOptions options = new AsyncOptions();
2options.DuplicateSignature = QueueableDuplicateSignature.Builder()
3                                .addId(UserInfo.getUserId())
4                                .addString('MyQueueable')
5                                .build();
6try {
7    System.enqueueJob(new MyQueueable(), options);
8} catch (DuplicateMessageException ex) {
9    //Exception is thrown if there is already an enqueued job with the same 
10    //signature
11    Assert.areEqual('Attempt to enqueue job with duplicate queueable signature',
12        ex.getMessage());
13}

This example builds the async job signature using ApexClass Id and the hash value of an sObject.

1AsyncOptions options = new AsyncOptions();
2options.DuplicateSignature = QueueableDuplicateSignature.Builder()
3                                .addInteger(System.hashCode(someAccount))
4                                .addId([SELECT Id FROM ApexClass 
5                                     WHERE Name='MyQueueable'].Id)
6                                .build();
7System.enqueueJob(new MyQueueable(), options);