Batch Apex Syntax and Example:

Syntax:

global class SynERPAccount_With_Account implements Database.Batchable<sObject>{

//Set up the base query

global Database.querylocator start(Database.BatchableContext BC)     {

return Database.getQueryLocator([select Id, Name from Account where status=’Active’]);

//Thestartmethod is called at the beginning of a batch Apex job. Use thestartmethod to collect the records or objects to be passed to the interface methodexecute

}

global void execute(Database.BatchableContext BC, List<sObjet> scope){

// Theexecutemethod is called for each batch of records passed to the method

}

global void finish(Database.BatchableContext BC){

// here send confirmation emails or execute post-processing operations

}

}

Example:

global class AccountUpdate implements Database.Batchable<sObject>{

//Set up the base query
global Database.querylocator start(Database.BatchableContext BC) {
return Database.getQueryLocator([select Id,Name from Account where status=’Active’]);
}

global void execute(Database.BatchableContext BC, list<Sony_Account_Team__c> scope) {
List<Account> updateAccount = new List<Account>();

for(sObject s : scope){Account a = (Account)s;
if(a.OwnerId==fromUserId){
a.OwnerId=toUserId;
updateAccount.add(a);
}
}
update updateAccount;
}

global void finish(Database.BatchableContext BC) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses(new String[] {email});
mail.setReplyTo(‘batch@acme.com’);
mail.setSenderDisplayName(‘Batch Processing’);
mail.setSubject(‘Batch Process Completed’);
mail.setPlainTextBody(‘Batch Process has completed’);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}

For more information on batch jobs, continue to Using Batch Apex.

Written by 

Salesforce MVP | Lightning Champion | 17x Salesforce Certified | Application Architect | 7x Trailhead Ranger | Techforce Services | Australia

Leave a Reply

Your email address will not be published. Required fields are marked *

*