Wednesday 16 January 2019

Batch Apex

1. What are transaction limits in apex?
Total number of SOQL queries issued1 - 100
Total number of records retrieved by SOQL queries - 50,000
Total number of records retrieved by Database.getQueryLocator - 10,000
Total number of records retrieved by a single SOSL query - 2,000
Total number of DML statements issued2 - 150
Total number of records processed as a result of DML statements, Approval.process, or database.emptyRecycleBin - 10000
Total number of callouts (HTTP requests or Web services calls) in a transaction - 100
Maximum cumulative timeout for all callouts (HTTP requests or Web services calls) in a transaction - 120
Maximum number of methods with the future annotation allowed per Apex invocation - 50
Maximum number of Apex jobs added to the queue with System.enqueueJob - 50
Total number of sendEmail methods allowed - 10
Maximum execution time for each Apex transaction - 10 minimum
Maximum number of push notification method calls allowed per Apex transaction - 10
Maximum number of push notifications that can be sent in each push notification method call - 2000


4. What is Database.Batchable interface?
To use batch Apex, write an Apex class that implements the Salesforce-provided interface 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.

5. Define the methods in Batchable interface?
Start()
Execute()
Finish()

6. What is purpose of Start method in batch apex?
Used to collect the records or objects to be passed to the interface method execute for processing.
This method is called once at the beginning of a Batch Apex job and returns either a Database.
Most of the time a QueryLocator does the trick with a simple SOQL query to generate the scope of objects in the batch job.
But if you need to do something crazy like loop through the results of an API call or pre-process records before being passed to the execute method, you might want to check out the Custom Iterators link in the Resources section.

7. What is the Database.QueryLocator ?
With the QueryLocator object, the governor limit for the total number of records retrieved by SOQL queries is bypassed and you can query up to 50 million records.
However, with an Iterable, the governor limit for the total number of records retrieved by SOQL queries is still enforced.
QueryLocator object or an Iterable that contains the records or objects passed to the job.

9. How to define the custom Iterable?
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];
   }
}

global class example implements iterable<Account>{
   global Iterator<Account> Iterator(){
      return new CustomIterable();
   }
}

global class batchClass implements Database.batchable<Account>{
   global Iterable<Account> start(Database.batchableContext info){
       return new example();
   }   
   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){   
   }
}

10. What is the use of execute method?
Used to collect the records or objects to be passed to the interface method execute for processing.
This method is called once at the beginning of a Batch Apex job and returns either a Database.QueryLocator object or an Iterable that contains the records or objects passed to the job.

11. How many times execute method is called?
For the execute method, it depends on you.

12. What is scope-of execute method?
Do DML Actions

13. Can we call callouts from batch apex?
global class BatchSync implements Database.Batchable<sObject>,   Database.AllowsCallouts {

 public String query = 'Select ID, Name from Account';
 global Database.QueryLocator start(Database.BatchableContext BC) {
    return Database.getQueryLocator(query);
 }

     global void execute(Database.BatchableContext BC, List<Account> records) {       
        String endpoint;       

        for ( integer i = 0; i< records.size(); i++ ){
         try {                 
          HttpRequest req = new HttpRequest();
          HttpResponse res = new HttpResponse();
          Http http = new Http();
          // Set values to Params

          endpoint = 'Your endpoint';

          req.setHeader('Authorization', header);
          req.setHeader('Content-Type', 'application/json');
          req.setEndpoint(endpoint);
          req.setMethod('POST');
          req.setBody('Information you wanna send');
          req.setCompressed(true); // This is imp according to SF, but please check if
                                 // the webservice accepts the info. Mine did not :P
                                 // Had to set it to false

          if (!Test.isRunningTest()) {     
            res = http.send(req);
            String sJson = res.getBody();
            System.debug('Str:' + res.getBody());
          }           
          // now do what u want to with response.             
          }
          catch (Exception e) {       
            System.debug('Error:' + e.getMessage() + 'LN:' + e.getLineNumber() );         
          }
       }
    } 

    global void finish(Database.BatchableContext BC){   
    }
}

14. Can we call another batch apex from batch apex?
Batch 1:
global class Batch1 implements Database.Batchable<Sobject>{

    //Method to get the data to be proceesed 
    global database.Querylocator Start(Database.BatchableContext bc){
        String query = 'Select Id, Name From Account Limit 1000';
        return Database.getQueryLocator(query);
    }


    //Method to execute the batch
    global void execute(Database.BatchableContext bc, Sobject[] scope){
        for(Sobject s : scope){
        Account a = (Account)s;
            // TO DO
            // add your logic
        }
    }

    //Method to be called after the excute
    global void finish(Database.BatchableContext bc){
        //Add your start code for the other batch job here
        Database.executeBatch(new Batch2());
    }
}

Batch 2:
global class Batch2 implements Database.Batchable<Sobject>{

    //Method to get the data to be proceesed 
    global database.Querylocator start(Database.BatchableContext bc){
        string query = 'Select Id, Name From Contact Limit 1000';
        return Database.getQueryLocator(query);
    }


    //Method to execute the batch
    global void execute(Database.BatchableContext bc, Sobject[] scope){
        for(Sobject s : scope){
        Contact c = (Contact)s;
            // TO DO
            // add your logic
        }
    }

    //Method to be called after the excute
    global void finish(Database.BatchableContext bc){

    }
}
15. How many callouts we can call in batch apex?
The upper limit now is 100 callouts ,which means if you have one callout in your execute method you can keep batch size as 100.
Say you have two callouts then your batch size can be 50 .

16. If you get Callouts Governing limits error how do you rectify?
Too many SOQL queries: 101
Since Apex runs on a multi-tenant platform, the Apex runtime engine strictly enforces limits to ensure code doesn't monopolize shared resources.
Avoid SOQL queries that are inside FOR loops.
Follow the key coding principals for Apex Code in our Developer's Guide.

17. Batch is synchronous or Asynchronous operations?
Asynchronous:
In a Asynchronous call, the thread will not wait until it completes its tasks before proceeding to next. Instead it proceeds to next leaving it run in separate thread. In a Asynchronous call, the code runs in multiple threads which helps to do many tasks as background jobs.
Example:
Batch
@future Annotation

Synchronous:
In a Synchronous call, the thread will wait until it completes its tasks before proceeding to next. In a Synchronous call, the code runs in single thread.
Example:
Trigger
Controller Extension
Custom Controller

21. What is the maximum size of the batch and minimum size of the batch?
Minimum size for Batch Apex in Salesforce is 1.
Maximum size for Batch Apex in Salesforce is 2000.

24. HOW to track the details of the current running Batch using BatchableContext?
Integer enqueuedJobs = [SELECT COUNT() FROM AsyncApexJob WHERE JobType='BatchApex' AND Status IN ('Processing','Preparing','Queued')] ;

if(enqueuedJobs >= 5){
    throw new TooManyBatchApexJobsException();
}

No comments:

Post a Comment

Batch Apex

1. What are transaction limits in apex? Total number of SOQL queries issued1 - 100 Total number of records retrieved by SOQL queries - 50...