Batch processing in Apex
Your class must implement Database.Batchable interface and should implement following method
- Start
- Execute
- Finish
Let create a simple Batch demo. Let say you want to append name of every account with '-ACC' and you have over 10,000 accounts then batch apex will do the job for you. Sorry this seems like a bad example but will make you understand the concept in a very simple way.
Create 2 class
- BatchAccount
- AccountDML
global class BatchAccount implements Database.Batchable<sObject>
{
global Database.QueryLocator start(Database.BatchableContext BC)
{
string Query = 'select id, name from account';
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<account> acc)
{
AccountDML.ProcessAccount(acc);
}
global void finish(Database.BatchableContext BC)
{
system.debug('Finished processing');
// You can also send email as well if thats what you want
}
}
public class AccountDML
{
public static void ProcessAccount (list<account> act)
{
list<account> actlist = new list<account>();
try
{
for(account a : act)
{
a.name = a.name+'ACC';
actlist.add(a);
}
database.SaveResult[] sr= database.update(actlist);
}
catch(exception ex)
{
system.debug(ex.getMessage());
}
}
}
For running the batch mode you go to run your code something like shown below
BatchAccount ba = new BatchAccount ();
database.executeBatch(ba,2);
Tada there you are. Now you are expert in writing batch apex. Well done :)
Comments
Post a Comment