Batch Apex vs Queueable Class in Salesforce

Both Batch Apex and Queueable Apex are used for asynchronous processing in Salesforce, but they have different use cases and characteristics. Let's define each and provide an example with sample code for both:

Batch Apex:

Batch Apex allows you to process large data sets by breaking them into smaller batches, which are processed asynchronously in the background. Batch Apex is designed for long-running processes and can handle millions of records efficiently.

Use Cases for Batch Apex:

Large-scale data processing, such as data cleansing, data migration, or data aggregation.

Complex calculations or transformations on a large volume of records.

Integration with external systems that involve processing large data sets.

Example:

Suppose you have a requirement to update the status of all opportunities with a certain criteria asynchronously. You can use Batch Apex to process these records in batches.

public class OpportunityBatch implements Database.Batchable<sObject> {
    public Database.QueryLocator start(Database.BatchableContext context) {
        return Database.getQueryLocator([SELECT Id, Name, StageName FROM Opportunity WHERE ...]);
    }

    public void execute(Database.BatchableContext context, List<Opportunity> scope) {
        for(Opportunity opp : scope) {
            // Perform processing on each Opportunity record
            opp.StageName = 'Closed Won';
        }
        update scope;
    }

    public void finish(Database.BatchableContext context) {
        // Perform any post-processing logic here
    }

}

To execute this batch job:

OpportunityBatch batchJob = new OpportunityBatch();

Database.executeBatch(batchJob);

Queueable Apex:

Queueable Apex allows you to add a job to the Apex job queue to be executed asynchronously. It provides more flexibility than Batch Apex and is suitable for short-running processes.

Use Cases for Queueable Apex:

Short-lived operations that can be executed independently and do not require splitting data into batches.

Callouts to external systems that require asynchronous processing.

Chaining multiple jobs together to perform sequential processing.

Example:

Suppose you have a requirement to send an email notification to users when a new lead is created. You can use Queueable Apex to send the email asynchronously.

public class LeadQueueable implements Queueable {
    public void execute(QueueableContext context) {
        // Send email notification to users
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.setToAddresses(new List<String>{'user1@example.com', 'user2@example.com'});
        email.setSubject('New Lead Created');
        email.setPlainTextBody('A new lead has been created in Salesforce.');
        Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{email});
    }

}

To execute this queueable job:

System.enqueueJob(new LeadQueueable());

Comparison:

Execution: Batch Apex processes data in batches, while Queueable Apex executes as a single job.

Governor Limits: Batch Apex has specific limits for the number of records processed in a batch, while Queueable Apex has its own set of limits for CPU time, heap size, and other resources.

Complexity: Batch Apex is suitable for complex processing on large data sets, while Queueable Apex is more lightweight and suitable for shorter operations.

Chaining: Queueable Apex allows you to chain multiple jobs together, while Batch Apex does not support chaining out-of-the-box.

In summary, Batch Apex and Queueable Apex both offer asynchronous processing capabilities in Salesforce, but they have different use cases and characteristics. Choose the one that best fits your specific requirements and processing needs.

Here's a comparison of Batch Apex and Queueable Apex in tabular format:











Here's a comparison of the governor limits for Batch Apex and Queueable Apex:









References - 

Queueable Apex

Batch Apex

Scheduled Apex

Comments

Popular posts from this blog

Introduction to Salesforce Agent Script: Build Predictable AI Agents

Anti-Patterns in Salesforce Agentforce: What to Avoid When Building AI Agents

MCP vs. Traditional APIs: Choosing the Right Integration Approach