Created
July 11, 2023 15:27
-
-
Save aidan-harding/48fa5d32c02c4fa2b9de62e2806cf194 to your computer and use it in GitHub Desktop.
Using Queueable Transaction Finalizer to avoid Dev Org Stack Depth limitation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public with sharing class InsertAccountsQueueable implements Queueable, Finalizer { | |
private Integer nAccounts; | |
private String name; | |
public InsertAccountsQueueable(Integer nAccounts, String name) { | |
this.nAccounts = nAccounts; | |
this.name = name; | |
} | |
public void execute(QueueableContext qc) { | |
if(nAccounts-- > 0) { | |
System.attachFinalizer(this); | |
insert new Account(Name = String.format(name, new List<String>{String.valueOf(nAccounts)})); | |
System.enqueueJob(this, 0); | |
} | |
} | |
public void execute(FinalizerContext fc) { | |
Exception e = fc.getException(); | |
if(e instanceof AsyncException && e?.getMessage()?.contains('Maximum stack depth has been reached') == true) { | |
System.enqueueJob(this, 0); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment