function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Lakshmi SLakshmi S 

Batch apex and schedulable apex

HI All

1.Example for Iterable in Batch apex?
2. Example for schedulable batch apex?
Best Answer chosen by Lakshmi S
SandhyaSandhya (Salesforce Developers) 
Hi Lakshmi Narasimha,

Please see the detailed explanation.
 
Batch Apex in Salesforce
To use batch Apex, you must write an Apex class that implements the Salesforce-provided interface Database.Batchable, and then invoke the class programmatically.
 
Start method


          The start method is called at the beginning of a batch Apex job. Use the start method to collect the records or objects to be passed to the interface method execute.

Syntax: global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {}

 This method returns either a Database.QueryLocator object or an iterable that contains the records or objects being passed into the job.
 
Execute Method

          The execute method is called for each batch of records passed to the method. Use this method to do all required processing for each chunk of data.

Syntax: global void execute(Database.BatchableContext BC, list<P>){}
 
This method takes the following:
o    A reference to the Database.BatchableContext object.
o    A list of sObjects, such as List<sObject>, or a list of parameterized types. If you are using a Database.QueryLocator, the returned list should be used.
Batches of records execute in the order they are received from the start method.
 
Finish Method

Syntax: global void finish(Database.BatchableContext BC){}
 
The finish method is called after all batches are processed. Use this method to send confirmation emails or execute post-processing operations.
Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1,000 records and is executed without the optional scope parameter from Database.executeBatch is considered five transactions of 200 records each.
The Apex governor limits are reset for each transaction. If the first transaction succeeds but the second fails, the database updates made in the first transaction are not rolled back.
 
Example of Batch Apex Class: 
 
Batch Schedule Class
global class batchContactUpdate implements Database.Batchable<sObject>
{
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        String query = 'SELECT Id, FirstName,LastName FROM Contact';
        return Database.getQueryLocator(query);
    }
 
    global void execute(Database.BatchableContext BC, List<Contact> scope)
    {
         for(Contact a : scope)
         {
             a.FirstName=a.FirstName+'FirstName is Updated';
             a.LastName = a.LastName +'LastName is updated';          
         }
         update scope;
    }  
    global void finish(Database.BatchableContext BC)
    {
    }
}
Schedule Class
-----------------------

 
global class BatchScheduleUpdate implements Schedulable
{
    global void execute(SchedulableContext sc)
    {
        // Implement any logic to be scheduled
       
        // We now call the batch class to be scheduled
        BatchContactUpdate b = new BatchContactUpdate ();
       
        //Parameters of ExecuteBatch(context,BatchSize)
        database.executebatch(b,200);
    }
   
}

Schedule from Developer Console
-------------------------------------------------
BatchScheduleUpdate batchSch=new BatchScheduleUpdate();
String sch='0 5 2 * * ?';
//System.schedule(String jobName, String cronExp, APEX_OBJECT schedulable);
System.schedule('Batch Schedule', sch , batchSch);


Please accept my solution as Best Answer if my reply was helpful. It will make it available for other as the proper solution. If you felt I went above and beyond, you can give me kudos.
 
Thanks and Regards
Sandhya

 

 

All Answers

SandhyaSandhya (Salesforce Developers) 
Hi Lakshmi Narasimha,

Please see the detailed explanation.
 
Batch Apex in Salesforce
To use batch Apex, you must write an Apex class that implements the Salesforce-provided interface Database.Batchable, and then invoke the class programmatically.
 
Start method


          The start method is called at the beginning of a batch Apex job. Use the start method to collect the records or objects to be passed to the interface method execute.

Syntax: global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {}

 This method returns either a Database.QueryLocator object or an iterable that contains the records or objects being passed into the job.
 
Execute Method

          The execute method is called for each batch of records passed to the method. Use this method to do all required processing for each chunk of data.

Syntax: global void execute(Database.BatchableContext BC, list<P>){}
 
This method takes the following:
o    A reference to the Database.BatchableContext object.
o    A list of sObjects, such as List<sObject>, or a list of parameterized types. If you are using a Database.QueryLocator, the returned list should be used.
Batches of records execute in the order they are received from the start method.
 
Finish Method

Syntax: global void finish(Database.BatchableContext BC){}
 
The finish method is called after all batches are processed. Use this method to send confirmation emails or execute post-processing operations.
Each execution of a batch Apex job is considered a discrete transaction. For example, a batch Apex job that contains 1,000 records and is executed without the optional scope parameter from Database.executeBatch is considered five transactions of 200 records each.
The Apex governor limits are reset for each transaction. If the first transaction succeeds but the second fails, the database updates made in the first transaction are not rolled back.
 
Example of Batch Apex Class: 
 
Batch Schedule Class
global class batchContactUpdate implements Database.Batchable<sObject>
{
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        String query = 'SELECT Id, FirstName,LastName FROM Contact';
        return Database.getQueryLocator(query);
    }
 
    global void execute(Database.BatchableContext BC, List<Contact> scope)
    {
         for(Contact a : scope)
         {
             a.FirstName=a.FirstName+'FirstName is Updated';
             a.LastName = a.LastName +'LastName is updated';          
         }
         update scope;
    }  
    global void finish(Database.BatchableContext BC)
    {
    }
}
Schedule Class
-----------------------

 
global class BatchScheduleUpdate implements Schedulable
{
    global void execute(SchedulableContext sc)
    {
        // Implement any logic to be scheduled
       
        // We now call the batch class to be scheduled
        BatchContactUpdate b = new BatchContactUpdate ();
       
        //Parameters of ExecuteBatch(context,BatchSize)
        database.executebatch(b,200);
    }
   
}

Schedule from Developer Console
-------------------------------------------------
BatchScheduleUpdate batchSch=new BatchScheduleUpdate();
String sch='0 5 2 * * ?';
//System.schedule(String jobName, String cronExp, APEX_OBJECT schedulable);
System.schedule('Batch Schedule', sch , batchSch);


Please accept my solution as Best Answer if my reply was helpful. It will make it available for other as the proper solution. If you felt I went above and beyond, you can give me kudos.
 
Thanks and Regards
Sandhya

 

 
This was selected as the best answer
Lakshmi SLakshmi S
*Hi Sandhya,* Nice explanation, thankyou very much. Could you please explain about Iterable concept in batch apex with example.
SandhyaSandhya (Salesforce Developers) 

Iterator:
________
An iterator traverses through every item in a collection. For example, in a while loop in Apex, you define a condition for exiting the loop, and you must provide some means of traversing the collection, that is, an iterator. 

The start() method returns either a Database.QueryLocator object or an iterable that contains the records or objects passed to the job.
When you’re using a simple query (SELECT) to generate the scope of objects in the batch job, use theDatabase.QueryLocator object. If you use a QueryLocator object, the governor limit for the total number of records retrieved by SOQL queries is bypassed. For example, a batch Apex job for the Account object can return aQueryLocator for all account records (up to 50 million records) in an org. Another example is a sharing recalculation for the Contact object that returns a QueryLocator for all account records in an org
.
Use the Iterable to create a complex scope for the batch job. You can also use the iterable to create your own custom process for iterating through the list

The iterator method must be declared as global or public. It creates a reference to the iterator that you can then use to traverse the data structure.

To use custom iterators, you must create an Apex class that implements the Iterator interface.

If you do not want to use a custom iterator with a list, but instead want to create your own data structure, you can use theIterable interface to generate the data structure.
The Iterable interface has the following method:

Name                         Returns             Description
iterator                       Iterator class    Returns a reference to the iterator for this interface.

The iterator method must be declared as global or public. It creates a reference to the iterator that you can then use to traverse the data structure.
In the following example a custom iterator iterates through a collection:
 
global class CustomIterable 
   implements Iterator<Account>{ 

   List<Account> accs {get; set;} 
   Integer i {get; set;} 

   public CustomIterable(){ 
       accs = 
       [SELECT Id, Name, 
       NumberOfEmployees 
       FROM Account 
       WHERE Name = 'false']; 
       i = 0; 
   }   

   global boolean hasNext(){ 
       if(i >= accs.size()) {
           return false; 
       } else {
           return true; 
       }
   }    

   global Account next(){ 
       // 8 is an arbitrary 
       // constant in this example
       // that represents the 
       // maximum size of the list.
       if(i == 8){return null;} 
       i++; 
       return accs[i-1]; 
   } 
}

The following calls the above code:
global class foo implements iterable<Account>{
   global Iterator<Account> Iterator(){
      return new CustomIterable();
   }
}

The following is a batch job that uses an iterator:
global class batchClass implements Database.batchable<Account>{ 
   global Iterable<Account> start(Database.batchableContext info){ 
       return new foo(); 
   }     
   global void execute(Database.batchableContext info, List<Account> scope){ 
       List<Account> accsToUpdate = new List<Account>(); 
       for(Account a : scope){ 
           a.Name = 'true'; 
           a.NumberOfEmployees = 69; 
           accsToUpdate.add(a); 
       } 
       update accsToUpdate; 
   }     
   global void finish(Database.batchableContext info){     
   } 
}

Please accept my solution as Best Answer if my reply was helpful. It will make it available for other as the proper solution. If you felt I went above and beyond, you can give me kudos.
 
Thanks and Regards
Sandhya

 
Lakshmi SLakshmi S
*Hi Sandhya,* *very helpful.*
SandhyaSandhya (Salesforce Developers) 
Hi Lakshmi Narasimha,

If this solves your question, please mark it as solved.

Thanks and Regards
sandhya
Lakshmi SLakshmi S
Nice Explanation.
Thanks
Lakshmi SLakshmi S
Hi Sandhya, I have a question please refer below i have 200 records on a batch while loading the records using data loader, i need to stop the records insertion after 10 records are inserted?how to achieve this?
Anvesh SinghAnvesh Singh
A very good explanation .However there is another thing I need to know is that how can I use finish method to schedule the same batch class quarterly.I know the cron String to schedule quarterly but I am not able to use that in finish method of batch apex class.
C RAJASEKARC RAJASEKAR
good explaination @sandhya