Salesforce Batchable Apex and Schedulable Apex with an Example
Salesforce provides two powerful features for executing code asynchronously: Batchable Apex and Schedulable Apex. These features allow developers to perform complex data processing tasks, integrations, or other long-running operations without impacting the user interface or causing performance issues. Below, I'll explain each feature along with an example for better understanding.
Batchable Apex:
Batchable Apex allows you to process large data sets in smaller, more manageable batches. It is particularly useful when dealing with large volumes of records that cannot be processed synchronously due to Salesforce's governor limits.
Here's an example of how Batchable Apex works:
// Example Batchable Apex classglobal class MyBatchableClass implements Database.Batchable<sObject> {
global Database.QueryLocator start(Database.BatchableContext BC) {
// Query the records you want to process
return Database.getQueryLocator([SELECT Id, Name FROM Account WHERE CreatedDate >= LAST_N_DAYS:7]);
}
global void execute(Database.BatchableContext BC, List<Account> scope) {
// Process each batch of records
for(Account acc : scope) {
// Perform data processing or other operations
acc.Description = 'Processed by Batchable Apex';
}
// Update the processed records
update scope;
}
global void finish(Database.BatchableContext BC) {
// Perform any post-processing tasks
}
}
Schedulable Apex:
Schedulable Apex allows you to schedule the execution of Apex classes to run at specific times or intervals. This feature is handy for automating tasks such as data cleanup, report generation, or integration with external systems.
Here's an example of how Schedulable Apex works:
// Example Schedulable Apex classglobal class MySchedulableClass implements Schedulable {
global void execute(SchedulableContext SC) {
// Query the records you want to process
List<Account> accounts = [SELECT Id, Name FROM Account WHERE CreatedDate >= LAST_N_DAYS:7];
// Perform data processing or other operations
for(Account acc : accounts) {
acc.Description = 'Processed by Schedulable Apex';
}
// Update the processed records
update accounts;
}
}
Scheduling the Job:
After defining the Batchable or Schedulable Apex class, you can schedule the job using either the Salesforce UI or programmatically using the System.schedule method. Here's how you can schedule the above Schedulable Apex class to run daily at midnight:
// Schedule the job to run daily at midnight
String jobName = 'MyScheduledJob';
String cronExp = '0 0 0 * * ?'; // Cron expression for daily at midnight
MySchedulableClass myJob = new MySchedulableClass();
System.schedule(jobName, cronExp, myJob);
Comments
Post a Comment