Showing posts with label Chain Batch Apex; Batch Jobs;. Show all posts
Showing posts with label Chain Batch Apex; Batch Jobs;. Show all posts

Thursday, March 16, 2023

Chain Batch Jobs in Salesforce

How to Chain Batch Jobs in Salesforce

First of all, we need to understand why do we need to chain the batch jobs?

Lets take an example:

We have two requirements to do in code. First we need to delete all the contacts and then insert the new contacts received from Integration. In this case, we can have two batch jobs. First job will delete the contacts and then second job will insert the new contacts.

In other words, Chaining jobs is useful if your process depends on another process to have run first. 

Call another batch in finish method so that all the processing of first job is completed and system will have the updated data before the second job.

global class MyBatchClass implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext bc){
        // collect the batches of records
    }
    global void execute(Database.BatchableContext bc, List<P> records){
        // process each batch of records
    }  
    global void finish(Database.BatchableContext bc){
        // call the other batch in finish method.    
        secondBatchJob obj = new secondBatchJob();    
        database.executeBatch(obj,<batch size>);
    }  
}    

Please share the blog and leave a comment about your thoughts.

Click here for more blogs

Mostly Viewed