Asynchronous Apex

|
| By Rushali kashyap

Asynchronous Apex in Salesforce allows developers to execute operations in a separate thread, enabling tasks to run in the background without impacting the user experience. This approach is particularly beneficial for handling long-running processes, callouts to external systems, and operations that require higher governor limits.

Key Benefits of Asynchronous Apex:

  • Improved User Experience: By executing long-running operations in the background, asynchronous processing ensures that users can continue interacting with the application without delays.
    Medium
  • Enhanced Performance: Offloading resource-intensive tasks to run asynchronously frees up system resources, allowing for more immediate user interactions and efficient processing.
  • Higher Governor Limits: Asynchronous Apex methods benefit from higher governor limits, such as increased SOQL query and heap size limits, enabling the processing of larger datasets and more complex operations.
    Salesforce Architects
  • Efficient Resource Utilization: By managing system resources more effectively, asynchronous processing allows for better handling of large data volumes and complex computations without impacting overall system performance.
  • Scalability: Asynchronous Apex can handle larger datasets and more complex operations without degrading system performance, making it suitable for scalable application development.

Types of Asynchronous Apex:

1. Future Methods: In Salesforce Apex, future methods enable developers to execute processes asynchronously, allowing long-running operations to run in the background without impacting the user experience. This is particularly useful for tasks such as callouts to external web services or operations that need to be isolated from the main execution thread.

Key Characteristics of Future Methods:

  • Static and Void: Future methods must be declared as static and can only return a void type.
  • Parameter Restrictions: They can accept only primitive data types or collections of primitive data types (such as List or Set). Passing sObjects or custom objects directly is not permitted.
  • Annotation: The @future annotation is used to define a future method.

Syntax Example:

public class MyTestClass {
@future
public static void myFutureTestMethod(List recordIds) {
// Perform operations asynchronously
}
}

Common Use Cases:

  • Callouts from Triggers: Since callouts are not allowed directly within triggers, a future method can be invoked to handle the callout asynchronously.
  • Resource-Intensive Operations: Tasks that require significant processing time can be offloaded to future methods to prevent delaying the main execution flow.

Limitations:

  • No Chaining: A future method cannot call another future method.
  • Order of Execution: The execution order of future methods is not guaranteed.
  • Governor Limits: While future methods provide higher governor limits compared to synchronous methods, they still have specific limits, such as a maximum of 50 future method invocations per Apex invocation.

2. Batch Apex: Batch Apex in Salesforce is a powerful tool designed to handle large-scale data operations that exceed standard processing limits. By breaking down extensive datasets into manageable chunks, Batch Apex processes records asynchronously, ensuring efficient resource utilization and adherence to governor limits.

Key Features of Batch Apex:

  • Efficient Data Processing: Batch Apex processes records in segments, allowing for operations on millions of records without hitting governor limits.
  • Asynchronous Execution: Tasks run in the background, ensuring that large data operations don’t impede user interactions.
  • Enhanced Governor Limits: Each batch execution is treated as a separate transaction, providing a fresh set of governor limits for each batch.

Implementing Batch Apex:

To utilize Batch Apex, create an Apex class that implements the Database.Batchable interface, which mandates the definition of three methods:

  1. start Method: Gather the records to be processed. It returns a Database.QueryLocator or an Iterable that contains the records or objects to be processed.
  2. execute Method: Processes each batch of data. The default batch size is 200 records, but it can be adjusted as needed.
  3. finish Method: Executes post-processing operations after all batches have been processed.

Example:

global class SampleBatch implements Database.Batchable {
global Database.QueryLocator start(Database.BatchableContext BC) {
// Query to collect records for processing
return Database.getQueryLocator('SELECT Id, Name FROM Account Limit 1000');
}

global void execute(Database.BatchableContext BC, List myScope) {
// Process each batch of records
List accountsToUpdate = new List();
for (SObject accObj : myScope) {
Account account = (Account)accObj ;
account.Name = account.Name + ' - Updated';
accountsToUpdate.add(account);
}
update accountsToUpdate;
}

global void finish(Database.BatchableContext BC) {
// Post-processing operations
System.debug('Batch Job Apex Completed!');
}
}

Executing the Batch Class:

To run the batch class, instantiate it and pass it to the Database.executeBatch method:

SampleBatch batch = new SampleBatch();
Database.executeBatch(batch, 100); // Batch size of 100

Best Practices:

  • Governor Limit Management: Be mindful of governor limits within the execute method to ensure efficient processing.
  • Batch Size Consideration: Choose an appropriate batch size based on the complexity of operations and system resources.
  • Error Handling: Implement robust error handling to manage exceptions without terminating the entire batch process.

3. Queueable Apex: Queueable Apex in Salesforce provides a robust framework for executing asynchronous operations, combining the simplicity of future methods with enhanced capabilities. By implementing the Queueable interface, developers can manage complex, long-running processes more effectively.

Key Advantages of Queueable Apex:

  • Enhanced Parameter Support: Unlike future methods, Queueable Apex allows the use of complex data types, such as sObjects and custom Apex types, as member variables. This flexibility facilitates more sophisticated processing scenarios.
  • Job Monitoring: Upon enqueuing a job using System.enqueueJob(), the method returns a job ID. This ID corresponds to an AsyncApexJob record, enabling developers to monitor the job’s progress through the Salesforce user interface or programmatically.
  • Job Chaining: Queueable Apex supports the chaining of jobs, allowing one job to initiate another upon completion. This feature is particularly useful for sequential processing tasks.

Implementing Queueable Apex:

To utilize Queueable Apex, create a class that implements the Queueable interface and define the execute method:
public class SampleQueueable implements Queueable {
public void execute(QueueableContext context) {
// Implement your asynchronous logic here
}
}

To enqueue the job for asynchronous execution:
ID jobId = System.enqueueJob(new SampleQueueable());

Use Cases for Queueable Apex:

  • Complex Business Processes: Ideal for handling intricate business logic that requires asynchronous processing.
  • Chained Operations: Suitable for scenarios where multiple asynchronous operations need to be executed in a specific sequence.
  • Enhanced Monitoring: Beneficial when tracking the status of asynchronous jobs is necessary.

4. Scheduled Apex: Scheduled Apex in Salesforce allows developers to execute Apex classes at specified times, making it ideal for automating recurring tasks such as daily or weekly maintenance. To implement Scheduled Apex, a class must implement the Schedulable interface and define the execute method.

Implementing Scheduled Apex:

1. Create the Apex Class:

  • Implement the Schedulable interface.
  • Define the execute method, which contains the code to be run at the scheduled time.

Example:

global class SampleMyScheduledClass implements Schedulable {
global void execute(SchedulableContext cts) {
// Your logic here
}
}

2. Schedule the Class:

  • Use the System.schedule method to set the class to run at a specific time.
  • Alternatively, schedule the class through the Salesforce user interface.

Using the System.schedule Method:

String myCronExpression = '0 0 5 * * ?'; // Every day at 5 AM
System.schedule('Daily Job', myCronExpression, new SampleMyScheduledClass());

3. Scheduling via the Salesforce UI:

  • Navigate to Setup.
  • First, enter “Apex Classes” in the Quick Find box and select it.
  • Then click on Schedule Apex.
  • Provide the job name, select the class, and set the schedule details.

Cron Expression Syntax:

The System.schedule method requires a cron expression to define the schedule. The syntax is:

Seconds Minutes Hours Day_of_month Month Day_of_week Optional_year

Example:

  • ‘0 0 5 * * ?’ – Runs every day at 5 AM.

Best Practices:

  • Governor Limits: Scheduled Apex runs in system mode, so be mindful of governor limits within your code.
  • Error Handling: Implement robust error handling to ensure that exceptions do not prevent future executions.
  • Monitoring: Regularly monitor scheduled jobs to ensure they are executing as expected.

Leave a Reply

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