Callouts from Batch Apex

Callouts from Batch Apex and Calling One Batch Apex to Another Batch | Salesforce Tutorial Guide

What number of callouts would we be able to bring in Batch Apex?

As far as possible currently is 100 callouts, which implies on the off chance that you have one callout in your execute strategy you can keep the batch size as 100. 

Suppose we have two callouts then our batch size can be 50 in size. 

On the off chance that you get Callouts governing cutoff points to mistake how would you redress it?

An excessive number of SOQL queries: 101 

Since Apex runs on a multi-tenant stage, the Apex runtime rigorously upholds cutoff points to guarantee code doesn't corner shared assets

Avoid the SOQL queries/query that is/are inside of the FOR loops

Let us know, Batch is Synchronous or Asynchronous operations

Asynchronous:

In an Asynchronous call, the thread won't wait until it finishes its jobs prior to continuing to next. Rather it continues to next leave it's anything but a different thread. In an Asynchronous call, the code runs in numerous threads which assists with doing numerous tasks as background occupations.

Example:- Batch, @future Annotation

dont miss out iconDon't forget to check out: How To Use Database.Stateful Interface In Batch Apex In Salesforce

Synchronous:

In a Synchronous call, the thread will wait until it completes its tasks before proceeding to the next. In a Synchronous call, the code runs in a single thread.

Example:

  • Trigger
  • Controller Extension
  • Custom Controller

Here is an example for Callout in Batch Apex

global class CalloutExample implements Database.Batchable<sObject>,   Database.AllowsCallouts {
    public String query = 'Select ID,FirstName, LastName, Email, Name from Contact;
    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 Parameters
                endpoint = 'Your endpoint will be here';
                req.setHeader('Authorization', header);
                req.setHeader('Content-Type', 'application/json');
                req.setEndpoint(endpoint);
                req.setMethod('POST');
                req.setBody('Json body you want to send');  
                req.setCompressed(true);
                // This is imp according to SF, but please check if the web service accepts the info.  
                // You have to set it to false.
                if (!Test.isRunningTest()) {      
                    res = http.send(req);
                    String Response = res.getBody();
                    System.debug('Response:' + res.getBody());
                }           
                // Here we do what we want to do with our response            
            }
            catch (Exception e) {       
                System.debug('Error is :' + e.getMessage() + 'LN:' + e.getLineNumber() );         
            }
        }
    } 
    global void finish(Database.BatchableContext BC){ }
}

How can we call another batch apex from batch apex

Batch Number 1:

global class OneToAnotherBatch implements Database.Batchable<Sobject>{
    //Here, Method to get the data to be processed 
    global database.Querylocator Start(Database.BatchableContext bc){
        String query = 'Select Id, FirstName, LastName, Name From Account Limit 500';
        return Database.getQueryLocator(query);
    }
    //Here is method to execute the batch
    global void execute(Database.BatchableContext bc, Sobject[] scope){
        for(Sobject s: scope){
            Account acct = (Account)s;
            // To do with your logic
            // Here we do what we want to do with your logic
        }
    }
    //Here is the method to be called after the execution.
    global void finish(Database.BatchableContext bc){
        //Add your start code for the other batch job here
        Database.executeBatch(new BatchTwo());
    }
}

Batch Number 2:

global class BatchTwo implements Database.Batchable<Sobject>{
    //Here, Method to get the data to be processed 
    global database.Querylocator start(Database.BatchableContext bc){
        string query = 'Select Id, FirstName, LastName, Name From Contact Limit 1000';
        return Database.getQueryLocator(query);
    }
    //Here is Method to execute the batch
    global void execute(Database.BatchableContext bc, Sobject[] scope){
        for(Sobject s : scope){
            Contact cont = (Contact)s;
            // To do with your logic
            // Here we do what we want to do with your logic
        }
    }
    //Here is Method to be called after the execute
    global void finish(Database.BatchableContext bc){}
}

dont miss out iconCheck out another amazing blog by Ratnesh here: Batch Apex in Salesforce (Basics, Governor Limits, Custom Iterable of Batch)

Maximum size of the batch and minimum size of the batch

The Minimum size for Batch Apex in Salesforce is 1.

The Maximum size for Batch Apex in Salesforce is 2000.

How can we track the details of the current running Batch using BatchableContext?

Integer Jobs= [SELECT COUNT() FROM AsyncApexJob WHERE JobType='BatchApex' AND Status IN ('Processing','Preparing','Queued')] ;
if(Jobs > 6){
    throw new TooManyBatchApexJobsException();
}

Responses

Popular Salesforce Blogs