Asynchronous Apex in Salesforce

 

Asynchronous Apex in Salesforce

  • Asynchronous Apex is a way to execute long-running operations in Salesforce without blocking the main thread of execution. 
  • It allows you to perform time-consuming operations like complex calculations, API calls, or bulk processing in the background. 
  • This helps prevent issues with governor limits (like CPU time and execution time) and ensures that the user experience remains responsive.

Why Use Asynchronous Apex?

Asynchronous Apex is useful for several reasons:
1. Avoid Governor Limits: 
  • Long-running processes can quickly hit governor limits, such as the maximum CPU time or heap size. 
  • By running the logic asynchronously, the system can break up the task into smaller chunks or execute the task later, preventing errors related to exceeding limits.
2. Improve User Experience: 

  • Asynchronous processing allows you to offload time-consuming tasks to the background.
  • Users can continue to interact with the application without being blocked by lengthy operations.
3. Handle Large Volumes of Data:
  • Asynchronous Apex (especially Batch Apex) is designed to process large datasets in chunks. 
  • This allows you to process millions of records without hitting limits.
4. Chaining Jobs:
  • Queueable Apex can be used to chain jobs, i.e., you can start a job and then call another job within the same execution context. 
  • This makes it easier to manage complex workflows.
5. External System Calls:
  • Asynchronous Apex can be used for making calls to external systems via HTTP requests. 
  • This is useful for integrating with third-party systems that might take time to respond.

Types of Asynchronous Apex:

  1. Future Methods
  2. Queueable Apex
  3. Batch Apex
  4. Schedulable Apex
Type Overview Common Scenarios
Future Run in their own thread, and do not start until resources are available. Web service callout
Queueable Similar to future methods, but provide additional job chaining and allow more complex data types to be used. Performing sequential processing operations with external Web services.
Batch Run large jobs that would exceed normal processing limits. Data cleansing, archiving of records, updating records in bulk
Schedulable Schedule Apex to run at a specified time. Daily or weekly tasks.


1. Future Methods Syntax And Example:
  • Future methods must be static methods, and can only return a void type.
  • The specified parameters must be primitive data types or collections of primitive data types.
 


    
        
trigger AccountTrigger on Account (before insert, before update) {
    if(Trigger.isBefore && (Trigger.isInsert || Trigger.isUpdate)) {
        AccountTriggerHandler.handleServices(trigger.new);
    } 
}
        
    

2. Queueable Apex Syntax And Example:

  • Queueable Apex is more flexible than future methods and can be used to chain jobs.


    
        
public class SomeClass implements Queueable {
    public void execute(QueueableContext context) {
        // awesome code here
    }
}
        
    

Invoking Queueable Apex:

To run the Queueable job, you use System.enqueueJob():

SomeClass job = new SomeClass();
System.enqueueJob(job);


3. Batch Apex Syntax And Example:



start method: 
  • The start() method is responsible for gathering the records or data that need to be processed. 
  • It typically returns a Database.QueryLocator or a list of SObjects that will be processed in batches.
execute() Method:
  • The execute() method processes each batch of records passed to it by the start() method.
  • The records passed to execute() are in the form of a list (the scope).
  • This method is called for each batch of records, and it is where the actual work happens — updating records, performing calculations, etc.
  • This method doesn’t return anything; instead, it typically performs DML operations (like insert, update, delete) or complex processing.
finish() Method: 
  • The finish() method is called after all batches have been processed.
  • It allows you to perform any final operations or cleanup tasks, such as sending notifications, logging success, or updating a status field.
  • This method is executed once all the records have been processed, after the final batch is completed.
  • It doesn’t return anything. You can use it to perform post-processing tasks like sending email notifications or executing other jobs (e.g., scheduling another batch).

4. Schedule Apex Syntax And Example:
  • Schedulable Apex allows you to schedule jobs to run at specific times, such as daily or weekly.
    
        
public class MyBatchClass implements Database.Batchable {
    public (Database.QueryLocator | Iterable) start(Database.BatchableContext bc) {
        // collect the batches of records or objects to be passed to execute
    }
    public void execute(Database.BatchableContext bc, List

records){ // process each batch of records } public void finish(Database.BatchableContext bc){ // execute any post-processing operations } }

Leave a Comment

Your email address will not be published. Required fields are marked *