Asynchronous Apex in Salesforce || Async Apex in Salesforce.
Comprehensive Note on Asynchronous Apex
Key Concepts of Asynchronous Apex
Advantages of Asynchronous Apex:
- User Efficiency: Users don’t have to wait for long-running processes to complete.
- Scalability: Processes run when system resources are available, allowing for parallel processing.
- Higher Limits: Asynchronous processes have higher governor limits compared to synchronous processes.
Types of Asynchronous Apex
- Future Methods
- Batch Apex
- Queueable Apex
- Scheduled Apex
Future Methods
public class SomeClass {
@future
public static void someFutureMethod(List
Key Points:
- Must be static and return
void. - Parameters must be primitive data types or collections of primitive types.
- Cannot call a future method from another future method.
- Use
@future(callout=true)for callouts.
Limits and Considerations:
- Limited to 50 future calls per Apex invocation.
- Maximum of 250,000 future calls per 24 hours.
- Future methods cannot be called from triggers or other future methods.
Testing Future Methods:
@isTest
public class SMSCalloutMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setBody('{"status":"success"}');
res.setStatusCode(200);
return res;
}
}
Batch Apex
public class MyBatchClass implements Database.Batchable
Key Points:
- Start: Collects records to be processed.
- Execute: Processes each batch of records.
- Finish: Executes post-processing logic.
- Stateful: Use
Database.Statefulto maintain state across transactions. - Batch Size: Default is 200, can be set up to 2000.
Iterable Batch Apex:
public class MyIterableBatchClass implements Database.Batchable
AllowCallout in Batch:
public class MyBatchClass implements Database.Batchable
Stateful in Batch:
public class MyBatchClass implements Database.Batchable
Invoking Batch Apex:
MyBatchClass myBatchObject = new MyBatchClass();
Id batchId = Database.executeBatch(myBatchObject, 100);
Batch Chaining:
global void finish(Database.BatchableContext BC) {
AccountBatch accBatch = new AccountBatch();
Id batchProcessId = Database.executeBatch(accBatch);
}
Queueable Apex
public class SomeClass implements Queueable {
public void execute(QueueableContext context) {
// Awesome code here
}
}
Key Points:
- Allows non-primitive types.
- Provides job chaining.
- Can monitor job progress via
AsyncApexJob.
Job Chaining:
public class FirstJob implements Queueable {
public void execute(QueueableContext context) {
// Process logic
System.enqueueJob(new SecondJob());
}
}
Enqueueing a Job:
SomeClass someClass = new SomeClass();
Id jobId = System.enqueueJob(someClass);
Scheduled Apex
public class SomeClass implements Schedulable {
public void execute(SchedulableContext ctx) {
// Awesome code here
}
}
Key Points:
- Use
System.schedule()to schedule jobs. - CRON expression is used to define the schedule.
Cron Expression:
Seconds Minutes Hours Day_of_month Month Day_of_week Optional_year
Example:
0 0 12 * * ? // Runs at 12 PM every day.
Example:
RemindOpptyOwners reminder = new RemindOpptyOwners();
String sch = '20 30 8 10 2 ?';
String jobID = System.schedule('Remind Opp Owners', sch, reminder);
Chaining and Scheduling
Chained Queue:
global void finish(Database.BatchableContext BC) {
AccountBatch accBatch = new AccountBatch();
Id batchProcessId = Database.executeBatch(accBatch);
}
Scheduleable:
public class MyScheduledClass implements Schedulable {
public void execute(SchedulableContext sc) {
MyBatchClass batch = new MyBatchClass();
Database.executeBatch(batch);
}
}
Additional Topics
Async Apex Limits:
- Maximum of 50 future calls per Apex invocation.
- Maximum of 250,000 future calls per 24 hours.
- Maximum of 100 scheduled jobs at a time.
Monitoring and Debugging:
- Use the Apex Jobs page to monitor asynchronous jobs.
- Query
AsyncApexJobandCronTriggerfor job details.
AsyncApexJob job = [SELECT Id, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors FROM AsyncApexJob WHERE Id = :batchId];
Best Practices:
- Error Handling: Implement robust error handling in asynchronous processes.
- Optimization: Optimize SOQL queries and avoid hitting governor limits.
- Testing: Use
Test.startTest()andTest.stopTest()to test asynchronous code.
Diagrams
Async Apex Overview
Async Apex
├── Future Methods
│ └── @future annotation
├── Batch Apex
│ ├── Database.Batchable
│ ├── start()
│ ├── execute()
│ └── finish()
├── Queueable Apex
│ ├── Queueable interface
│ └── System.enqueueJob()
└── Scheduled Apex
├── Schedulable interface
└── System.schedule()
Batch Apex Lifecycle
Start → Execute (Batch 1) → Execute (Batch 2) → ... → Finish
Key Differences
| Feature | Future Methods | Queueable Apex | Batch Apex |
|---|---|---|---|
| Data Types | Primitive only | Non-primitive allowed | Non-primitive allowed |
| Job Chaining | Not supported | Supported | Supported (up to 5 chains) |
| Monitoring | Limited | Yes (via AsyncApexJob) | Yes (via AsyncApexJob) |
| Use Case | Simple callouts | Complex processing | Large data volumes |
Conclusion
Asynchronous Apex provides a robust way to handle long-running processes, large data volumes, and scheduled tasks in Salesforce. By understanding the differences and use cases for Future Methods, Batch Apex, Queueable Apex, and Scheduled Apex, developers can choose the right tool for the job and ensure efficient, scalable, and maintainable code. Additionally, mastering topics like Iterable Batch Apex, AllowCallout in Batch, Stateful in Batch, and Chained Queue will help you tackle complex scenarios and ace your interviews.
Comments
Post a Comment