Batch apex code samples with solution
Batch class Scenario
1. Write a batch class to send a mail to all the related contacts where Account revenue is greater than 10000?
ANS:
public with sharing class BatchclassforPractice implements Database.Batchable<sObject>,Database.Stateful {
Global Integer count=0;
public List<String> conlist = new List<String>();
public Database.QueryLocator start(Databse.BatchableContext bc)
{
return Database.getQueryLocator('select id from Account where revenue >10000');
}
public void execute(Databse.BatchableContext bc,List<Account> acclist)
{
for(Account acc : acclist)
{
acclist1.add(acc.id);
}
for(contact con :[select id from contact where Account in : acclist1])
{
conlist.add(con.Email);
}
}
public void finish(Database.BatchableContext bc)
{
List<Messaging.SingleEmailMessage>Emaillist = new List<Messaging.SingleEmailMessage>();
Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
message.setToAddresses(conlist);
message.setSubject('Record is created');
message.setPlainTextBody('your account revenue is greater than 10000 ');
Emaillist.add(message);
Messaging.sendEmail(Emaillist);
}
}
BatchclassforPractice bc = new BatchclassforPractice();
databse.executeBatch(bc);
Comments