๐ Asynchronous Apex in Salesforce
Asynchronous Apex is used for long-running, resource-intensive, or bulk operations that can't run within the standard synchronous limits. Salesforce provides several async mechanisms to meet different needs.
---๐ Why Use Async Apex?
- ✅ Handle large volumes of data
- ✅ Avoid governor limits
- ✅ Perform non-blocking tasks (e.g., callouts)
- ✅ Execute scheduled tasks
1️⃣ Batch Apex
Used to process millions of records in manageable chunks asynchronously.
Key Methods:
start()
– Returns a query locator or iterableexecute()
– Processes each batchfinish()
– Final logic (e.g., email notifications)
Example: Batch Apex
global class AccountBatch 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) {
for (Account acc : scope) {
acc.Name += ' - Updated';
}
update scope;
}
global void finish(Database.BatchableContext bc) {
System.debug('Batch Job Finished');
}
}
๐งช To Run:
AccountBatch ab = new AccountBatch();
Database.executeBatch(ab, 200);
---
2️⃣ Queueable Apex
Queueable Apex is like a lightweight batch that allows chaining jobs and supports complex logic and callouts.
Example: Queueable Apex
public class UpdateContactQueue implements Queueable {
public void execute(QueueableContext context) {
List<Contact> contacts = [SELECT Id, Email FROM Contact WHERE Email != null];
for (Contact c : contacts) {
c.Email = c.Email.toLowerCase();
}
update contacts;
}
}
๐งช To Enqueue:
System.enqueueJob(new UpdateContactQueue());
---
3️⃣ Scheduled Apex
Use Scheduled Apex to run logic at specific times or intervals.
Steps:
- Implement
Schedulable
interface - Deploy or schedule via UI or code
Example: Scheduled Apex
public class MonthlyJob implements Schedulable {
public void execute(SchedulableContext sc) {
System.debug('Running monthly job!');
}
}
๐งช To Schedule:
String cronExp = '0 0 8 1 * ?'; // 8 AM on 1st of every month
System.schedule('Monthly Job', cronExp, new MonthlyJob());
---
4️⃣ Future Methods
Future methods are simple ways to run async logic. Best for quick, non-blocking operations like callouts or updates.
Rules:
- Must be
@future
- Only supports primitive types and collections as parameters
- Can’t return values
- Limited governor scope
Example: Future Method
public class EmailUtils {
@future
public static void sendWelcomeEmail(String email) {
System.debug('Sending email to: ' + email);
// Logic to send email (mocked)
}
}
๐งช To Call:
EmailUtils.sendWelcomeEmail('test@example.com');
---
๐ Comparison Table
Feature | Batch Apex | Queueable | Scheduled | Future |
---|---|---|---|---|
Use Case | Large data sets | Chained logic, callouts | Timed jobs | Quick async tasks |
Supports Chaining | ❌ (Only via finish) | ✅ | ✅ | ❌ |
Supports Callouts | ✅ (Must implement Database.AllowsCallouts ) |
✅ | ✅ | ✅ |
Execution Timing | As triggered | As triggered | By schedule | As triggered |
✅ Best Practices
- Use Batch Apex for data volumes > 10,000
- Use Queueable Apex for flexible async logic and chaining
- Use Scheduled Apex for recurring tasks
- Use Future methods for simple, fire-and-forget jobs