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 

I am Sakthivel Madesh, a certified Salesforce Advanced Developer & Administrator working on Salesforce Technology since 2011. I am currently working in Techforce Services as Sr. Salesforce Developer. I have worked on multiple technologies Like PHP, Java, Salesforce, I am very passionate about Salesforce and to earn 15x Salesforce Certification. I love Trailhead for learning Salesforce Skill and Become a Trailhead 5x Ranger too. I Love to Learn & Share my Salesforce knowledge to Salesforce Learners/Beginner using My Blog and Salesforce Community.

Leave a Reply