Power of Asynchronous Apex: Benefits and Insights

Aman Garg
4 min readSep 22, 2023

Introduction

Salesforce is renowned for its ability to provide businesses with comprehensive customer relationship management (CRM) solutions. To supercharge its functionality, Salesforce introduced Asynchronous Apex, a powerful feature that enables developers to perform background processing and schedule tasks, ultimately enhancing performance and productivity. In this blog post, we’ll explore the world of Asynchronous Apex, and its benefits, and delve into some key details to help you harness its potential.

What is Asynchronous Apex?

Asynchronous Apex is a Salesforce feature that allows developers to execute code outside the traditional request-response model. In simpler terms, it lets you run processes in the background, freeing up resources for other tasks. This capability is especially valuable when dealing with time-consuming operations like data imports, email notifications, and data processing.

Benefits of Asynchronous Apex

  1. Improved User Experience: Asynchronous Apex ensures that time-consuming tasks don’t block the user interface. This leads to a more responsive and seamless user experience, as users can continue working without waiting for long-running processes to complete.
  2. Scalability: By offloading tasks to the background, Asynchronous Apex enhances your Salesforce application’s scalability. It prevents resource contention and allows your system to handle an increasing number of requests without performance degradation.
  3. Enhanced Performance: Asynchronous processing optimizes resource allocation, resulting in better performance and reduced execution time for critical operations.
  4. Robust Error Handling: Asynchronous Apex provides robust error handling mechanisms. It can automatically retry failed jobs, send notifications, and log errors for easy troubleshooting.
  5. Bulk Data Processing: Salesforce bulk data operations like data imports, updates, and deletions can be resource-intensive. Asynchronous Apex is particularly beneficial for handling large volumes of data efficiently.

Types of Asynchronous Apex

Salesforce offers different ways to implement asynchronous processing:

Batch Apex: Batch Apex is suitable for processing large datasets efficiently. It divides a large job into smaller, manageable chunks, making it easier to handle.

Example: Updating Contact Records

public class UpdateContactsBatch implements Database.Batchable<SObject> {
public Database.QueryLocator start(Database.BatchableContext context) {
return Database.getQueryLocator('SELECT Id, FirstName, LastName FROM Contact WHERE LastModifiedDate < LAST_N_DAYS:30');
}

public void execute(Database.BatchableContext context, List<Contact> scope) {
// Update the contact records
for (Contact con : scope) {
con.FirstName = 'Updated';
con.LastName = 'Contact';
}
update scope;
}

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

Queueable Apex: Queueable Apex is used to schedule and prioritize background jobs. It’s perfect for scenarios where you want to control the order of execution or pause/resume processing.

Example: Sending Email Notifications

public class EmailNotificationQueueable implements Queueable {
String recipient;
String message;

public EmailNotificationQueueable(String recipient, String message) {
this.recipient = recipient;
this.message = message;
}

public void execute(QueueableContext context) {
// Send an email to the recipient
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setToAddresses(new List<String>{recipient});
email.setSubject('Notification');
email.setPlainTextBody(message);
Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{email});
}
}

Scheduled Apex: Scheduled Apex lets you schedule classes to run at specific times or on a recurring basis. It’s ideal for automating routine tasks, such as generating reports or sending email notifications.

Example: Send an email using a Schedulable class

global class EmailSenderScheduled implements Schedulable {
global void execute(SchedulableContext ctx) {
// Define the email details
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses(new String[]{'recipient@example.com'});
mail.setSubject('Scheduled Email');
mail.setPlainTextBody('This is a scheduled email sent from Salesforce.');

// Send the email
List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
emails.add(mail);
Messaging.sendEmail(emails);
}
}

Future Methods: Future methods allow you to run code asynchronously when resources are available. They’re commonly used for one-off tasks that need to be completed in the background.

public class EmailSender {
@future
public static void sendEmail(String recipient, String subject, String body) {
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setToAddresses(new String[]{recipient});
email.setSubject(subject);
email.setPlainTextBody(body);

try {
Messaging.sendEmail(new Messaging.SingleEmailMessage[]{email});
} catch (Exception e) {
System.debug('Email sending failed: ' + e.getMessage());
}
}
}

Considerations and Best Practices

While Asynchronous Apex offers many benefits, it’s essential to use it judiciously and follow best practices to avoid potential pitfalls:

  1. Governance Limits: Salesforce enforces governor limits for Asynchronous Apex. Be aware of these limits to ensure smooth execution.
  2. Bulk Data Handling: When working with bulk data, consider batch processing or Queueable Apex to prevent hitting governor limits.
  3. Logging and Monitoring: Implement robust error handling, logging, and monitoring to track the progress and health of your asynchronous jobs.
  4. Optimize Code: Write efficient code to minimize execution time and resource consumption.

Conclusion

Asynchronous Apex is a game-changer for Salesforce developers and administrators. Its ability to run processes in the background, improve user experience, enhance scalability, and optimize performance makes it an invaluable tool for building efficient and responsive Salesforce applications. By understanding the different types of Asynchronous Apex and following best practices, you can harness its full potential and take your CRM to the next level.

--

--

Aman Garg

Sr. Salesforce Developer || 5x Salesforce Certified || 2x Copado Certified || Salesforce Mentor || Founder of Salesforce Learners