0% found this document useful (0 votes)
13 views6 pages

Async Apex in Salesforce

Uploaded by

Ajay Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views6 pages

Async Apex in Salesforce

Uploaded by

Ajay Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Asynchronous Apex in Salesforce

Asynchronous Apex in Salesforce refers to the execution of code


outside the normal processing flow of a Salesforce transaction. Instead of
running immediately, asynchronous processes are scheduled to execute at
a later time. This concept is essential for handling long-running
operations, preventing transaction timeouts, and optimizing system
performance.

Why Asynchronous Apex Matters?

Handling Large Data Volumes: Salesforce is not just a CRM; it’s a data
management platform. As your data volumes grow, you may encounter
issues with governor limits and execution timeouts. Asynchronous
processes help you overcome these limitations.

Improved User Experience: Users expect responsive applications.


Asynchronous processing ensures that your Salesforce application remains
responsive and doesn’t get bogged down by time-consuming operations.

Long-Running Operations: Certain tasks, such as data migrations,


integrations, and batch processing, can take a significant amount of time.
Asynchronous Apex allows you to delegate these tasks to run in the
background, freeing up resources for other operations.

Use Cases for Asynchronous Apex

Batch Processing: One of the most common use cases for asynchronous
Apex is batch processing. It enables you to process records in chunks,
efficiently handling large data volumes.

Scheduled Jobs: Use scheduled jobs to automate tasks, such as sending


daily reports or performing data clean-up operations during off-peak
hours.

Future Methods: Future methods allow you to offload time-consuming


operations triggered by user interactions to ensure a smooth user
experience.

Queueable Apex: Queueable Apex provides a more flexible alternative to


future methods, allowing for better chaining of asynchronous processes.
Platform Events: Asynchronous processing can also be triggered by
platform events, enabling real-time integration and event-driven
architecture.

Benefits of Asynchronous Apex

Optimized Performance: By moving time-consuming operations out of


the synchronous transaction, you improve overall system performance
and responsiveness.

Governor Limits Mitigation: Asynchronous processes have their own


set of governor limits, which are often more permissive than those of
synchronous code. This mitigates governor limit issues.

Scalability: As your data and user base grow, asynchronous processing


scales with your needs, ensuring your application remains efficient.

Error Handling: Asynchronous processes can handle errors more


gracefully by logging them and allowing the main transaction to proceed
without failure.

Best Practices for Asynchronous Apex

Bulkify Your Code: Always ensure that your asynchronous code is


capable of handling large data volumes to avoid hitting governor limits.

Use Proper Exception Handling: Implement robust error handling and


logging mechanisms to capture and troubleshoot any issues that may
arise during asynchronous processing.

Monitor and Analyze: Keep an eye on the performance of your


asynchronous jobs using Salesforce’s monitoring tools and logs to identify
bottlenecks or areas for improvement.
Consider Limits: While asynchronous processing has more relaxed
governor limits, it’s essential to understand and work within those limits to
avoid unexpected issues.

Testing: Comprehensive testing, including unit tests and integration


tests, is crucial to ensure the reliability of your asynchronous code.

Asynchronous Apex with examples:

Future Methods:

Example:

@future

public static void sendEmailAsync(String recipient, String subject, String


body) {

// Send an email asynchronously

Messaging.SingleEmailMessage email = new


Messaging.SingleEmailMessage();

email.setToAddresses(new List<String>{recipient});

email.setSubject(subject);

email.setPlainTextBody(body);

Messaging.sendEmail(new
List<Messaging.SingleEmailMessage>{email});

Queueable Apex:

Purpose: Queueable Apex allows for more controlled execution of


asynchronous tasks and is suitable for complex processing. You can
enqueue jobs for execution and pass data to them.

Example:

public class MyQueueable implements Queueable {


public void execute(QueueableContext context) {

// Perform asynchronous operations

// Enqueue the job

MyQueueable job = new MyQueueable();

System.enqueueJob(job);

Batch Apex:

Purpose: Batch Apex is used for processing large sets of records in smaller
chunks. It’s ideal for complex data processing tasks like data
transformations, updates, or inserts.

Example:

global class MyBatch implements Database.Batchable<sObject> {

global Database.QueryLocator start(Database.BatchableContext bc) {

return Database.getQueryLocator(‘SELECT Id FROM Account’);

global void execute(Database.BatchableContext bc, List<Account>


scope) {

// Process records in chunks

global void finish(Database.BatchableContext bc) {

// Perform post-processing tasks

}
}

// Start the batch job

MyBatch batchJob = new MyBatch();

Database.executeBatch(batchJob);

Scheduled Apex:

Purpose: Scheduled Apex allows you to schedule code execution at


specific times or on a recurring basis. It’s useful for automating tasks like
data clean-up or report generation.

Example:

global class MyScheduledJob implements Schedulable {

global void execute(SchedulableContext ctx) {

// Perform scheduled operations

// Schedule the job to run daily at midnight

String cronExpression = ‘0 0 0 * * ?’;

System.schedule(‘MyScheduledJob’, cronExpression, new


MyScheduledJob());

Platform Events:

Purpose: Platform Events allow you to publish and subscribe to events


within Salesforce or between Salesforce and external systems. They
facilitate real-time event-driven architecture.

Example:

// Publish a platform event


EventBus.publish(new MyEvent__e(Field1__c = ‘Value1’, Field2__c =
‘Value2’));

Asynchronous Triggers:

Purpose: Asynchronous Triggers, also known as Asynchronous Trigger


Handlers, allow you to execute logic after a record has been inserted,
updated, or deleted without delaying the user’s interaction with the
system.

Example:

trigger MyTrigger on MyObject__c (after insert) {

// Perform asynchronous operations here

These are the primary types of Asynchronous Apex in Salesforce, each


serving different purposes. Choosing the right one depends on your
specific use case and the complexity of the task you need to perform
asynchronously. By leveraging Asynchronous Apex, you can optimize the
performance and scalability of your Salesforce applications while providing
a better user experience.

Please go through the below link

https://www.sfdckid.com/2019/07/salesforce-asynchronous-
apex.html#google_vignette

You might also like