Ad
Ad
Ad
Beginner Dev

Dev Tip 6: Chaining of Batchjobs in salesforce

Pinterest LinkedIn Tumblr

In this post, We will try to understand how to initiate Batchjob from Other Batch Job. Every Batch job consists of three methods such as Start, Execute, and Finish methods.

In the start method, we will query for the list of records from the desired object. Generally, We use Querylocator as it could hold up to 50 million records.

Execute method – All the business logic is processed inside the Execute method by using the list of records from the Start method

Finish method – This is the last method inside batch apex which will be executed after the Execute method. We could send an Email or Call a Batch job or do both inside this method.

Ex: We have two Batchjobs such as AccountBatch and ContactBatch.We could call ContactBatch from the finish method of AccountBatch

global class AccountBatch implements Database.Batchable<sObject>

{

    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)

    {

       List<Account> accList = new List<Account>();

     for(Account acc : scope)

        {

            acc.Name = “Account Processed”;

            accList.add(acc);

        }

        update accList;

    }

    global void finish(Database.BatchableContext BC)

{

// Call Contactbatch job from AccountBatch

    ContactBatchJob contactJob = new ContactBatchJob();

   database.executebatch(contactJob);

    }

}

Write A Comment