You are on page 1of 7

# Batch Apex:

Database.Batchable
Method : start() //execute()//Finish() .
--------------------------------------------------------------------
global class Batch_Example_2 implements Database.Batchable<sobject>{
global Database.QueryLocator start(Database.BatchableContext bc){
string query='select id,name, type from Opportunity';
return Database.getQueryLocator(query); //this can retrun upto 50 Milion
records
}
//Batch1 Batch2 Batch3 Batch4
Batch5
//0-100 101-200 201-300 301-
400 401-500
//execute(scope) execute(scope) execute(scope) execute(scope)
execute(scope)
global void execute(Database.BatchableContext bc,List<Opportunity> scope){
for(Opportunity op:scope){
op.type='New Customer';
}
update scope;
//system.debug('subJob:'+bc.getChildJobId());
}
global void finish(Database.BatchableContext bc){
AsyncApexJob job=[select id,status,JobType from AsyncApexJob where Id=:
bc.getJobId()];
system.debug('Status:'+job.Status);
}
}
---->
Apex code:Open Execute Anonomous Window.
Batch_Example_2 be=new Batch_Example_2();
Id jobId=Database.executebatch(be,5);
---->
// default size:200
Id jobId=Database.executebatch(be,10); // 10-10 records per batch.
[size 1-2000]
------->
set -- job-> Apex Jobs.
1]when you going through larger record then you hit the govener limit so we used
apex batch.
2]Batch Apex operates over small batches of records, covering your entire record
set and breaking the processing down to manageable chunks.
3]Batch Apex allows you to handle more number of records and manipulate them by
using a specific syntax.
4] Method : start() //execute()//Finish() .
-------->
Database.Bathcable --> Interface #interface always global so we used global
class.
start,execute,finish
Database.BatchableContext---> getJob, getChildJobId().
Database.stateful[interface]
Database.AllowsCallouts [interface for the webservice]
What is BatchApex:
saleforce implemating the architecture of multitant to avoide dominance of
perticular applications , to implemanting this mult
arechitecture there are same limitation called governer limits like total number
DML-150 webservie-100, No.SOOL-40, Email inviquation -10,
Queue size-60 lac.
but when you trying to work large data,huge data then using batchApex, batchApex
will break the operation into sub operations [job in subjob]
every job/subjob run independetly.
-------------------
#Create a bath apex which will fetch all the accounts and update rating as hot.
global class Batch_Example_3 implements
Database.Batchable<sobject>,Database.stateful {
global integer count=0;
global static integer size=0;
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> scope){
for(Account a:scope){
count=count+1;
size=size+1;
}
}
global void finish(Database.BatchableContext bc){
Account acc=new Account();
acc.Name='BatchApex';
acc.Description='count :'+count+ 'Size :'+Size;
insert acc;
}
}
-->
Apex code:Open Execute Anonomous Window.
Batch_Example_3 be=new Batch_Example_3();
Id jobId=Database.executebatch(be,10);
-----------------------------------------------------------------------------------
-----------------------------------------
global class Bath_Example_4 implements Database.Batchable<sObject>{
global Database.QueryLocator start(Database.BatchableContext BC){
string query = 'Select id,name, type from Account where type=null';
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<Account> Scope){
for(Account a:scope){
a.type='Prospect';

}
update scope;
}
global void finish(Database.BatchableContext BC){
system.debug('Account Update Type=prospect');
}

}
-------->
Bath_Example_4 acc=new Bath_Example_4();
Database.executeBatch(BC);
-----------------------------------------------------------------------------------
------------------------------------------------
global class Batch_Example_5 implements Database.Batchable<sObject>{
global Database.QueryLocator start(Database.BatchableContext BC){
string query='select First_Name__c,Gender__c from Staff_Detail__c';
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<Staff_Detail__c> scope){
for(Staff_Detail__c s:scope){
if(s.Gender__c=='Male'){
s.First_Name__c='Mr.'+s.First_Name__c;
} else{
if(s.Gender__c=='Female'){
s.First_Name__c='Miss.'+s.First_Name__c;
}
}
}
update scope;
}
global void finish(Database.BatchableContext BC){
System.debug('Update the Saluasation of Staff');

}
}
------->
Batch_Example_5 BC=new Batch_Example_5();
Database.executeBatch(BC,5); //5 record per Batch.
---------------------------------------------------------------------------------
global class Batch_Example_6 implements Database.Batchable<sobject> {
global Database.QueryLocator start(Database.BatchableContext BC){
string Query='Select First_Name__c,Gender__c from students_details__c';
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<students_details__c>
scope){
for(students_details__c s:scope){
if(s.Gender__c =='Male'){
s.First_Name__c='Mr.'+s.First_Name__c;
} else if(s.Gender__c=='Female')
{
s.First_Name__c='Miss.'+s.First_Name__c;
}
Database.update(scope);
}
}
global void finish(Database.BatchableContext BC){
system.debug('Salutation Update to Student Details');
}
}
------>
Batch_Example_6 BC=new Batch_Example_6();
Database.executeBatch(BC,2);
-----------------------------------------------------------------------------------
-----------
/* Develope a simple Batch Apex which will
* Update the contact Fax with Account Fax if Contact Fax is Null
* Update contact mobile phone with Account Phone if contact phone is Null
* Update Email With atulkhope.sfdc@gmail.com
* Update description with Account Name +Account Industry +Rating +contact Email
* Send the Notification to user atulkhope.sfdc@gmail.com when batch executed
successfully
* user of Database.stateful interface to send the information about successs and
failed records*/

global class Batch_Class_Contact_8 implements Database.Batchable<sObject>{


global Database.QueryLocator start(Database.BatchableContext BC){
string Query='select Id,Name,Fax,Email,MobilePhone,Description,
Account.Name,Account.Rating,Account.Phone,Account.Fax,Account.Industry from
Contact';
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<Contact>contactList){
integer size = contactList.size();
for(Integer i=0;i<size;i++){
Contact con=contactList.get(i);
if(con.Fax==null || con.Fax==''){
con.Fax=con.Account.Fax;
}
if(con.MobilePhone==null || con.MobilePhone==''){
con.MobilePhone=con.Account.Phone;
}
con.Email='atulkhope.sfdc@gmail.com';
con.Description=con.Account.Name+' '+con.Account.Rating+'
'+con.Account.Industry+' '+con.Email;
}
update contactList;
}
global void finish(Database.BatchableContext BC){

Messaging.SingleEmailMessage email=new Messaging.SingleEmailMessage();


email.setSubject('Status of the Batch Class : Batch_Class_Contact_8');
email.setSenderDisplayName('SFDC Atul Khope');
email.setHtmlBody('Dear User, Bath Processed');
List<string> emailTo=new List<string>();
emailTo.add('atulkhope@gmail.com');
email.setToAddresses(emailTo);
Messaging.SingleEmailMessage[]emailList=new
List<Messaging.SingleEmailMessage>();
emailList.add(email);
Messaging.sendEmail(emailList,false);
}
}
---------->
Batch_Class_Contact_8 batch=new Batch_Class_Contact_8();
Database.executeBatch(batch);
-----------------------------------------------------------------------------------
-----------------------------------------------
global class Batch_Class_Contact_8 implements
Database.Batchable<sObject>,Database.stateful{
global integer total_size =0;
global integer fail_size =0;
global integer success_size=0;
global Database.QueryLocator start(Database.BatchableContext BC){
string Query='select Id,Name,Fax,Email,MobilePhone,Description,
Account.Name,Account.Rating,Account.Phone,Account.Fax,Account.Industry from
Contact';
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<Contact>contactList){
integer size = contactList.size();
total_size=total_size+size;
/*
* total_size=0;
* batch chunk -2
* 0+2=2
*batch chunk =3 2+2=4
*/
for(Integer i=0;i<size;i++){
Contact con=contactList.get(i);
if(con.Fax==null || con.Fax==''){
con.Fax=con.Account.Fax;
}
if(con.MobilePhone==null || con.MobilePhone==''){
con.MobilePhone=con.Account.Phone;
}
con.Email='atulkhope.sfdc@gmail.com';
con.Description=con.Account.Name+' '+con.Account.Rating+'
'+con.Account.Industry+' '+con.Email;
}
// update contactList;
Database.SaveResult[]result=Database.update(contactList,false); //2-1,
success, 1 fail
integer size_result=result.size();
for(integer i=0;i<size_result;i++){
Database.SaveResult sr=result.get(i);
if(sr.isSuccess()){
success_size +=1;
}
else{
fail_size +=1;
}
}
}
global void finish(Database.BatchableContext BC){

Messaging.SingleEmailMessage email=new Messaging.SingleEmailMessage();


email.setSubject('Status of the Batch Class : Batch_Class_Contact_8');
email.setSenderDisplayName('SFDC Atul Khope');
email.setHtmlBody('Dear User,<br/> Bath Processed'+
'<br/>Total Records:' +Total_size+
'<br/>Success Count:' +success_size+
'<br/>Fail Count:' +fail_size);
List<string> emailTo=new List<string>();
emailTo.add('atulkhope.sfdc@gmail.com');
email.setToAddresses(emailTo);
Messaging.SingleEmailMessage[]emailList=new
List<Messaging.SingleEmailMessage>();
emailList.add(email);
Messaging.sendEmail(emailList,false);
}
}
------>
Batch_Class_Contact_8 batch=new Batch_Class_Contact_8();
Database.executeBatch(batch,2);
===================================================================================
================================
global class Batch_Class_Contact_8 implements
Database.Batchable<sObject>,Database.stateful{
global integer total_size =0;
global integer fail_size =0;
global integer success_size=0;
global Database.QueryLocator start(Database.BatchableContext BC){
string Query='select Id,Name,Fax,Email,MobilePhone,Description,
Account.Name,Account.Rating,Account.Phone,Account.Fax,Account.Industry from
Contact';
/* getjobId
getChildJobId
AsynApexJob
*/
AsyncApexJob[] apexjobs=[select id,
ApexClassId,ApexClass.Name,
NumberofErrors,JobItemsProcessed,
TotalJobItems,Status
From AsyncApexJob
where Id=:BC.getJobId()];
system.debug('#### Batch Status of Start Method :'+apexjobs);
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<Contact>contactList){
AsyncApexJob[] apexjobs_parent=[select id,
ApexClassId,ApexClass.Name,
NumberofErrors,JobItemsProcessed,
TotalJobItems,Status
From AsyncApexJob
where Id=:BC.getJobId()];
system.debug('#### Batch Status Execute parent Method :'+apexjobs_parent);
AsyncApexJob[] apexjobs_child=[select id,
ApexClassId,ApexClass.Name,
NumberofErrors,JobItemsProcessed,
TotalJobItems,Status
From AsyncApexJob
where Id=:BC.getChildJobId()];
system.debug('#### Batch Status Execute Child Method :'+apexjobs_child);
integer size = contactList.size();
total_size=total_size+size;
/*
* total_size=0;
* batch chunk -2
* 0+2=2
*batch chunk =3 2+2=4
*/
for(Integer i=0;i<size;i++){
Contact con=contactList.get(i);
if(con.Fax==null || con.Fax==''){
con.Fax=con.Account.Fax;
}
if(con.MobilePhone==null || con.MobilePhone==''){
con.MobilePhone=con.Account.Phone;
}
con.Email='atulkhope.sfdc@gmail.com';
con.Description=con.Account.Name+' '+con.Account.Rating+'
'+con.Account.Industry+' '+con.Email;
}
// update contactList;
Database.SaveResult[]result=Database.update(contactList,false); //2-1,
success, 1 fail
integer size_result=result.size();
for(integer i=0;i<size_result;i++){
Database.SaveResult sr=result.get(i);
if(sr.isSuccess()){
success_size +=1;
}
else{
fail_size +=1;
}
}
}
global void finish(Database.BatchableContext BC){
AsyncApexJob[] apexjobs=[select id,
ApexClassId,ApexClass.Name,
NumberofErrors,JobItemsProcessed,
TotalJobItems,Status
From AsyncApexJob
where Id=:BC.getJobId()];
system.debug('#### Batch Status of finish Method :'+apexjobs);

Messaging.SingleEmailMessage email=new Messaging.SingleEmailMessage();


email.setSubject('Status of the Batch Class : Batch_Class_Contact_8');
email.setSenderDisplayName('SFDC Atul Khope');
email.setHtmlBody('Dear User,<br/> Bath Processed'+
'<br/>Total Records:' +Total_size+
'<br/>Success Count:' +success_size+
'<br/>Fail Count:' +fail_size);
List<string> emailTo=new List<string>();
emailTo.add('atulkhope.sfdc@gmail.com');
email.setToAddresses(emailTo);
Messaging.SingleEmailMessage[]emailList=new
List<Messaging.SingleEmailMessage>();
emailList.add(email);
Messaging.sendEmail(emailList,false);
}
}
----->
Batch_Class_Contact_8 batch=new Batch_Class_Contact_8();
Database.executeBatch(batch,20);

-----------------------------------------------------------------------------------
---------------------------------

You might also like