Skip to main content

Asynchronous Apex Triggers - Summer ‘19

Asynchronous Apex triggers are change event triggers that run asynchronously after a database transaction is completed. They are ‘after-insert’ triggers and can be defined with the after insert keywords. They can be created the same way you create regular Apex triggers. You set the trigger to use a change event object instead of an sObject. The change event object name is suffixed with ChangeEvent. For example, Account change event object is named AccountChangeEvent. The change event object name for the custom object is suffixed with __ChangeEvent.


How does it work?

When a record is created or updated, Change Data Capture publishes an event and a change event trigger can then process that event asynchronously.
Let’s look at an example transaction. Whenever an opportunity record is created or updated, you need to check whether the corresponding account is qualified to be a high priority customer. This process of qualifying high priority customers is very limit-intensive and computationally slow.
For this scenario, we can enable Change Data Capture for the Opportunity object, then implement the complex business logic in the OpportunityChangeAsyncTrigger (asynchronous Apex trigger).
When the opportunity record is created or changed, the OpportunityChangeAsyncTrigger is automatically fired and executes the complex business logic defined in AccountClassifier. Each change event processed in the trigger contains the changed record fields and metadata information about the change in header fields.

Pictorial representation of transactional flow for the example transaction]
Let’s write the code by using the CLI from the VS Code terminal. You can create the asynchronous trigger by using the following command. You can then write the code with in this trigger block and push it to your org.

sfdx force:apex:trigger:create -n OpportunityChangeAsyncTrigger -s OpportunityChangeEvent -e 'after insert' -d 'force-app/main/default/triggers'

In this code, Trigger.new() contains list of change events after the database operation. In the for loop, we are extracting the Opportunity ID, which is processed to identify the high priority Account. The classifyAccountmethod of AccountClassifier class is very limit-intensive and computationally slow, hence we are calling it outside the transaction in this asynchronous trigger. You can also create this trigger from the Developer Console by selecting File→New→ Apex Trigger and then OpportunityChangeEvent for the sObject.

trigger OpportunityChangeAsyncTrigger on OpportunityChangeEvent (after insert) {
    List<OpportunityChangeEvent> changes = Trigger.new;
    
    Set<String> oppIds = new Set<String>();
    
    //Get all record Ids for this change and add it to a set for further processing
    for(OpportunityChangeEvent opp: changes){
        List<String> recordIds = opp.ChangeEventHeader.getRecordIds();
        oppIds.addAll(recordIds);
    }
    
    
    //Perform heavy computation operation which may take a lot of time
    AccountClassifier classifier = new AccountClassifier();
    Map<String, String> highPriorityAccounts = classifier.classifyAccount(new List<String>(oppIds));
}

Comments

  1. In this manner my partner Wesley Virgin's biography launches with this SHOCKING AND CONTROVERSIAL VIDEO.

    Wesley was in the army-and shortly after leaving-he found hidden, "self mind control" secrets that the government and others used to get everything they want.

    As it turns out, these are the EXACT same secrets many celebrities (notably those who "come out of nothing") and top business people used to become rich and famous.

    You probably know that you use less than 10% of your brain.

    Mostly, that's because the majority of your brain's power is UNCONSCIOUS.

    Perhaps that expression has even taken place INSIDE your own head... as it did in my good friend Wesley Virgin's head about seven years ago, while riding an unregistered, garbage bucket of a car with a suspended driver's license and with $3.20 on his banking card.

    "I'm absolutely fed up with going through life paycheck to paycheck! Why can't I become successful?"

    You've taken part in those thoughts, isn't it right?

    Your success story is waiting to start. All you have to do is in YOURSELF.

    Watch Wesley Virgin's Video Now!

    ReplyDelete

Post a Comment

Popular posts from this blog

Mashup Integration in Salesforce

During preparation for TA certification exam, I came across a word Mashup for integration a number of times. I explored about it and below is description:- Mashups, sometimes called “composites,” are hybrid applications created by bringing together several data sources and Web services to create a new application or to add value to an existing application. Behind the scenes, mashups may require different levels of integration, depending on whether the mashed-up data is only meant to be viewed, whether it can be edited, and whether data is actually transferred between systems. There are three types of mashup:- Client Presentation Mashup - In this type of mashup the integration takes place strictly at the visual level. It makes possible to view data from two or more applications in a browser,  without actually moving data between the applications. Example - Google Maps. Client Service Mashup - As mashups evolve, they are becoming more complex and sophisticated. Client ser

Grant Access Using Hierarchies

Problem There is a custom object say 'XYZ' and OWD for this is set to ' Private ', which means record of this can be seen by only owner and users above in role-hierarchy and territory. However, to share this with other user, we can manually share it. The problem is that I don't want other users, who are above in role-hierarchy and territory of the user with whom record has shared, can see it. Solution We can un-check ' Grant Access Using Hierarchies ' check box for object 'XYZ' on 'Sharing Settings' page. We can go to Setup >> Security Controls >> Sharing Settings and click on ' Edit ' button. On the edit page, we can un-check ' Grant Access Using Hierarchies ' for required object.  Major uses of 'Grant Access Using Hierarchies' are:- If you disable the Grant Access Using Hierarchies option, sharing with a role or territory and subordinates only shares with the users directly asso

ReadOnly Annotation

Use Case:- You want to show up to 10000 record on single VF page. Count of records based upon some business requirement where number of records could go up to 1 million. So far, it was not possible to achieve above in VF page because of following limitations:- The maximum number of items in a collection that can be iterated over using components such as <apex:dataTable> , <apex:dataList> , and <apex:repeat> is 1000. Normally, queries for a single Visualforce page request may not retrieve more than 50,000 rows. Solution:- But with API version 23.0 , salesforce has introduced ' ReadOnly ' annotation which has following functionality/restriction:- The @ReadOnly annotation allows you to perform unrestricted queries against the Force.comdatabase. All other limits still apply. It's important to note that this annotation, while removing the limit of the number of returned rows for a request, blocks you from performing the following operations