Asynchronous Apex in Salesforce is a powerful feature in Salesforce that allows you to execute long-running or resource-intensive operations in the background, without blocking the user’s interaction. In simpler terms, it helps to run tasks in the background, so the user doesn’t have to wait for the task to finish. This is especially useful when dealing with complex business processes that take time.
Let’s explore Asynchronous Apex and how it works in Salesforce.
What is Asynchronous Apex?
In Salesforce, tasks are generally classified as synchronous or asynchronous based on how they execute.
- Synchronous Apex: When you execute a task synchronously, it means the task runs immediately, and the user has to wait for it to finish before they can continue working.
- Asynchronous Apex: In asynchronous execution, the task runs in the background while the user can continue working without any interruptions. This is useful for long-running tasks that would otherwise take too long if executed synchronously.
Difference Between Synchronous and Asynchronous Apex
Feature | Synchronous Apex | Asynchronous Apex |
---|---|---|
Execution | Tasks run immediately, blocking user interaction until completion. | Tasks are executed in the background, allowing the user to continue working. |
Response Time | Requires immediate response. | Suitable for delayed or non-immediate response tasks. |
Use Case | Simple, quick tasks like validation and database updates. | Long-running tasks like sending emails, processing large datasets, or making callouts. |
Governor Limits | Stricter limits (e.g., 100 SOQL queries per transaction). | Relaxed limits (e.g., higher SOQL limits, longer execution times). |
Transaction Timeout | Limited to a shorter time frame (10 seconds for synchronous web services). | Longer execution time (up to 60 minutes for some asynchronous processes). |
In short, asynchronous Apex is ideal when you want to run processes that take time and don’t need to be completed immediately.
Governor Limits for Asynchronous Apex
Governor limits are essential in Salesforce to ensure that no single process monopolizes shared resources. When using Asynchronous Apex, certain governor limits are more relaxed compared to synchronous Apex.
- SOQL Queries:
- Synchronous Apex limit: 100 SOQL queries per transaction.
- Asynchronous Apex limit: 200 SOQL queries per transaction.
- Execution Time:
- Synchronous transactions have a shorter time limit, typically 10 seconds.
- Asynchronous Apex allows longer execution times, up to 60 minutes.
- Heap Size:
- Synchronous Apex limit: 6 MB.
- Asynchronous Apex limit: 12 MB.
These relaxed limits in Asynchronous Apex allow developers to handle larger datasets, perform more queries, and execute more complex logic without hitting governor limits quickly.
Types of Asynchronous Apex
There are several types of asynchronous processes in Salesforce that you can use depending on your requirements:
- Future Methods:
- The simplest type of asynchronous Apex.Used to perform tasks like making callouts to external services or processing large records in the background.Use Case: Sending an email after an account is updated or making an HTTP callout to an external system.
public class AsyncExample {
@future
public static void sendEmail(String emailAddress) {
// Code to send email
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setToAddresses(new String[]{emailAddress});
email.setSubject('Hello from Salesforce');
email.setPlainTextBody('This is an asynchronous email!');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });
}
}
- Batch Apex:
- Used to process large volumes of data.
- Use Case: Processing millions of records that need to be updated in the database.
global class MyBatchClass implements Database.Batchable<sObject> {
global Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator('SELECT Id, Name FROM Account');
}
global void execute(Database.BatchableContext bc, List<Account> scope) {
// Process each batch of Accounts
for (Account acc : scope) {
acc.Name += ' - Processed';
}
update scope;
}
global void finish(Database.BatchableContext bc) {
// Finalize the batch
System.debug('Batch job complete');
}
}
- Queueable Apex:
- Similar to future methods but offers more control, such as chaining jobs.Allows the creation of job queues, where jobs run sequentially. Use Case: Chaining multiple jobs, or when future methods don’t provide enough flexibility.
public class MyQueueableJob implements Queueable {
public void execute(QueueableContext context) {
// Code to execute asynchronously
System.debug('Queueable job running...');
}
}
- Scheduled Apex:
- Allows you to schedule Apex code to run at specific times. Can be useful for recurring tasks like sending weekly reports. Use Case: Automating data backups or running daily reports.
public class ScheduledJob implements Schedulable {
public void execute(SchedulableContext sc) {
// Code to run at a scheduled time
System.debug('Scheduled job running...');
}
}
// Scheduling the job
String cronExp = '0 0 12 * * ?'; // Runs every day at noon
System.schedule('DailyJob', cronExp, new ScheduledJob());
Conclusion
Asynchronous Apex is an essential tool for Salesforce developers, particularly for handling tasks that require long execution times, heavy data processing, or tasks that don’t need immediate user interaction. By understanding the various types of asynchronous processes and how they can help you bypass certain governor limits, you’ll be able to write efficient and scalable Salesforce applications.
Understanding the difference between Synchronous Apex and Asynchronous Apex helps ensure you select the right approach for your business requirements, especially as your applications grow and evolve.