Asynchronous processing is a must-have skill for any Salesforce developer working with large data volumes, long-running operations, or external integrations. In this post, we’ll demystify Apex’s async toolbox: when to use each tool, common pitfalls, and patterns for reliable, scalable jobs.
- Governor Limits: Async jobs have higher limits (e.g., more SOQL queries, DML statements, CPU time).
- User Experience: Offload slow operations so users don’t wait.
- Scalability: Process thousands or millions of records without hitting limits.
Best for: Complex logic, chaining jobs, handling small-to-medium batches.
public class MyQueueable implements Queueable {
public void execute(QueueableContext context) {
// Your logic here
List<Account> accts = [SELECT Id FROM Account WHERE CreatedDate = LAST_N_DAYS:1];
for (Account a : accts) {
a.Description = 'Processed by Queueable!';
}
update accts;
}
}
// Enqueue:
System.enqueueJob(new MyQueueable());
Best for: Processing large data volumes, up to 50 million records.
global class MyBatch implements Database.Batchable<SObject> {
global Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator('SELECT Id FROM Contact');
}
global void execute(Database.BatchableContext bc, List<Contact> contacts) {
for (Contact c : contacts) {
c.Description = 'Processed by Batch!';
}
update contacts;
}
global void finish(Database.BatchableContext bc) {
// Post-processing logic
}
}
// Start batch:
Database.executeBatch(new MyBatch());
Best for: Simple, stateless, fire-and-forget operations (e.g., callouts).
@future(callout=true)
public static void sendDataToExternalSystem(Id recordId) {
// Callout logic here
}
- Chaining: Use Queueables or Batch’s
finish()
to kick off follow-up jobs. - Error Handling: Wrap async logic in try/catch and log exceptions for monitoring.
- Bulkification: Even async jobs should process collections, not single records.
- Limits: Remember limits still apply! For example, max 50 concurrent batches.
public class FirstJob implements Queueable {
public void execute(QueueableContext context) {
// Do first batch of work, then chain:
System.enqueueJob(new SecondJob());
}
}
public class SecondJob implements Queueable {
public void execute(QueueableContext context) {
// Do follow-up work
}
}
Knowing when and how to use Apex’s async features unlocks scalable, performant solutions on Salesforce. Choose the right tool for your scenario, handle errors gracefully, and always build for bulk!
Happy coding! 🚀
Post a Comment