Writing Batch Jobs/Apex in Salesforce
Batch Apex
When to use Batch Apex, think of Batch Job when data is huge, with a min of 10,000 to 1 million records, like updating records nightly manner, weekly or Monthly batch job really helpful.
To use batch Apex, One must write an Apex class that implements the Salesforce-provided interface Database.Batchable, and then invoke the class programmatically.
Following are main/mandatory methods to write Apex Batch Job,
- Start grab the record you want to operate upon
- Execute (perform the operation)
- Finish (close, and if required send confirmation email)
global class Batch_Class_Example implements Database.Batchable < sObject > {
// Constructor (Optional) - you can use this for Initialisation just like in your controllers
global Batch_Class_Example() {
}
// Start Method
global Database.QueryLocator start(Database.BatchableContext BC) {
return Database.getQueryLocator('<Query_goes_here>');
// returns up to 50 million records
}
// Execute Method
global void execute(Database.BatchableContext BC, List < sObject > scope) {
// Batch Logic goes here
for(Sobject s : scope){
// perform for loop logic here
}
}
// Finish Method
global void finish(Database.BatchableContext BC) {
// Use this method to send confirmation emails or execute post-processing operations
}
}
To invoke a batch class, instantiate it first and then call Database.executeBatch with the instance of your batch class:
Batch_Class_Example bObj = new Batch_Class_Example();
Id batchprocessid = Database.executeBatch(bObj, <batch_size>);
Default size is 200
Monitoring
To monitor or stop the execution of the batch Apex job, navigate as follows. From Setup, click Monitoring | Apex Jobs or Jobs | Apex Jobs.