In this training, you create and execute a batch class.
Batch Apex
Batch Apex is used to run large jobs (think thousands or millions of records!) that would exceed normal processing limits. Using Batch Apex, you can process records asynchronously in batches (hence the name, “Batch Apex”) to stay within platform limits. If you have a lot of records to process, for example, data cleansing or archiving, Batch Apex is probably your best solution.
Step 1: Create the Batch Class
- In the Developer Console, select File > New > Apex Class, specify
SendReminderEmail
as the class name and click OK. - Make the class global, implement the
Batchable
interface, and define the three methods of the interface.
global class SendReminderEmail implements Database.Batchable<sObject> {
global Database.QueryLocator start(Database.BatchableContext bc) {
}
global void execute(Database.BatchableContext bc, List<Speaker__c> scope) {
}
global void finish(Database.BatchableContext bc) {
}
}
3.Declare three instance variables to store the query, the email subject, and the email body.
global String query;
global String subject;
global String body;
4.Define a constructor implemented as follows.
global SendReminderEmail(String query, String subject, String body) {
this.query = query;
this.subject = subject;
this.body = body;
}
5.Implement the start()
method as follows.
global Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator(query);
}
6.Implement the execute()
method as follows.
global void execute(Database.BatchableContext bc, List<Speaker__c> scope) {
String[] addresses = new String[]{},
subjects = new String[]{},
messages = new String[]{};
for (Speaker__c speaker : scope) {
addresses.add(speaker.Email__c);
subjects.add(this.subject);
messages.add(this.body);
}
EmailManager.sendMail(addresses, subjects, messages);
}
7.Save the file.
Step 2: Run the Batch
- Make sure you have assigned your own email address to one of the speakers.
- In the Developer Console, click Debug > Open Execute Anonymous Window.
- Type the following Apex code.
String q = ‘SELECT First_Name__c, Last_Name__c, Email__c FROM Speaker__c WHERE Email__c != null’;
SendReminderEmail batch = new SendReminderEmail(q, ‘Final Reminder’, ‘The conference starts next Monday’);
Database.executeBatch(batch)
4.Click Execute.
5.Check your email.
This Training is very useful to learn about batch class in salesforce.
We are the ISV Partners and Please reach us for custom development => www.merfantz.com