Gubbas Digi Communications

Gubbas Digi Communications

Batch Apex


                                  Batch Apex


Using Batch Apex:
      To use batch Apex, write an Apex class that implements the Salesforce provided  Database.Batchable and then invoke the class programmatically.

To monitor or stop the execution of the batch Apex job, from Setup, enter Apex Jobs in the Quick Find box, then select Apex Jobs.
Implementing the "Database.Batchable Interface".

The "Database.Batchable interface" contains three methods that must be implemented.
1.Start method
2.Execute
3.Finish

Start method :

Syntax:
      global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc)
     {
      //code;
      }
  • To collect the records or objects to pass to the interface method execute, call the start method at the beginning of a batch Apex job.
  • This 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 the "Database.QueryLocator object". 
               For example, a batch Apex job for the Account object can return a QueryLocator 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.
 
 Execute method:

         Syntax :
            global  void execute(Database.BatchableContext bc,List<sObject> scope)
            {
              //code block
             }

1. To do the required processing for each chunk of data, use the execute method. This method is called for    each batch of records that you pass to it.
   
   This method takes the following:

        a. A reference to the Database.BatchableContext object.
        b. A list of sObjects, such as List<sObject>, or a list of parameterized types. If you are using a    Database.QueryLocator, use the returned list.

2.Batches of records tend to execute in the order in which they’re received from the start method.
3.However, the order in which batches of records execute depends on various factors. The order of execution isn’t guaranteed.

Finish method:

        Syntax :
              global void finish(Database.BatchableContext bc)
              {
               //code block;
               }

 1.To send confirmation emails or execute post-processing operations, use the finish method. This method is   called after all batches are processed.
2.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.
 3.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.Using "Database.BatchableContext".


Example questions:

 1. Write an Apex Batch class in your Salesforce developer org to delete Accounts created in 
      last 10 days.
Ans:
            global class accountDelRecDate implements Database.Batchable<sObject>
            {
              global Database.QueryLocator start(Database.BatchableContext bc)
              {
                String query;
                 query ='SELECT Id,CreatedDate FROM Account WHERE CreatedDate>=Date.Today()-10';
                  return Database.getQueryLocator(query);
              }
            
               global void execute(Database.BatchableContext bc, List<Account> scope)
               {
                 System.debug(scope);
                  delete scope;
                }
         
                global void finish(Datase.BatchableContext bc)
                 {
            
                  }
          }

   Execute in anonymous window:
         
            accountDelRecDate b=new accountDelRecDate();
            Database.executeBatch(b); 


    2. Schedule the above class to run twice for every 12 hours a day.  
      
    Ans:
              String cron_code='0 0 12,0 * * ?;
             accountDelRecDate b=new accountDelRecDate();
              System.schedule('Batch class runs',cron_code,b); 
               
     3. Write a Script to delete the above Schedule Jobs.     
  
   Ans:
              String cron_code='0 0 12,0 * * ?;
             accountDelRecDate b=new accountDelRecDate();
             Id jobId =System.schedule('Batch class runs',cron_code,b); 
             System.abortJob(jobId);

                  
                
  
 4. Create Batch to update the Account “Count” field(Create this field) with sum of number contacts       related to that Account. 
  
 Ans:

        global batchCount implements Database.Batchable<sObject>
        {
             global Database.QueryLocator 

 start(Database.BatchableContext bc)
             { 
            String query;
                 query='SELECT Id,Name,(SELECT Id FROM Contacts)  FROM Account' ;

          return Database.getQueryLocator(query);
                 
                 
    
              }

               global void execute(Database.BatchableContext bc, 

       List<Account> scope)
             {
                List<Account> accLst=new List<Account>();  
                for(Account acc: scope)
                 {
                    acc.Count__c=acc.Contacts.size();
                    accLst.add(acc);
                  }
                  update accLst;
                 }

                 global void finish(Database.BatchableContext bc)
                 
        {

         }

              }


              Execute in anonymus window :  
      
                        batchCount bc=new batchCount();
                        Database.executeBatch(bc,2);
                         
                                                                         

                 
                                                                            


  









No comments:

Post a Comment