Apex · Salesforce

Alternative solution for Apex Batch job? Apex Queueable – Use Case

Many client have apex batch queue limitation – means only 5 apex queue can be execute at same time, many client crossing 5 queue and waiting for long time in “Queued” job.

To over come that limitation – salesforce has another feature called “Apex Queueable”. This interface work as future call but you can chain the same Queueable job again and again OR other Queueable job.

When you want to process thousands of records and do some business logic and update salesforce data or callout to external system – you can use Queueable interface to process partial data and chain same job again continue remaining records.

Use Case: Daily job need to update account with sum of closed opportunity amount.

Problem: there are N number batch job running over the night. We can’t use apex batch job to archive this functionality.

Solution: We can use Apex Queueable to process 100 account per execution and chain the same job to run again and again.

Sample Code:

public class queueableApexJob implements Queueable {

    public void execute(QueueableContext context) {
        //Pulling 100 accounts per transaction
        map<Id, Account> mapAccount = new map<Id, Account>([Select Id, Acc_Opportunity_Total__c,Amount_Cal_Processed_Date__c from Account where Amount_Cal_Processed_Date__c != TODAY limit 100]);
        //Pulling opportunity that closed today based on above Accounts
        list<Opportunity> lstOpportunity = [Select Id, AccountId, Amount from Opportunity where AccountId =:mapAccount.keySet() and CloseDate = TODAY];
        //Processing opportunity and populating sum of opportunity amount
        for(Opportunity iterator : lstOpportunity) {
            mapAccount.get(AccountId).Acc_Opportunity_Total__c += iterator.Amount;
            mapAccount.get(AccountId).Amount_Cal_Processed_Date__c = TODAY;
        }
        if(mapAccount.size() > 0) {
            //Updating Account
            update mapAccount.values();
            //This will stop when there is not account to process
            System.enqueueJob(new queueableApexJob()); //Chained same job again to process remaining records
        }
    }

}

 

Click here to read more about Queueable and Limitations.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s