function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
JSchneiderJSchneider 

Can I begin a batch job upon completion of another batch job?

I've several batch jobs that are running smoothly and have no desire to combine the two.  I would like however, when one batch job finishes, for it to call the next batch job.  I assume it goes along the lines of adding database.executeBatch(NextBatchName,BatchSize);  I just cannot figure out where.

This is the exisiting batch class that I'm working with.
global class batchProAssetBuilder implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String myProduct = 'xyz';
        String query = 'SELECT Id,Run_Asset_Builder_Pro__c FROM Account WHERE PIN_Code__c != null AND Product__c = :myProduct';
        return Database.getQueryLocator(query);
    }
   
    global void execute(Database.BatchableContext BC, List<Account> scope) {
         for(Account a : scope)
         {
             a.Run_Asset_Builder_Pro__c = true;            
         }
         update scope;
    }   
    
global void finish(Database.BatchableContext BC){

 // Get the AsyncApexJob that represents the Batch job using the Id from the BatchableContext
 AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed,
  TotalJobItems, CreatedBy.Email, ExtendedStatus
  from AsyncApexJob where Id = :BC.getJobId()];
 
 // Email the Batch Job's submitter that the Job is finished.
 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
 String[] toAddresses = new String[] {a.CreatedBy.Email};
 mail.setToAddresses(toAddresses);
 mail.setSubject('BatchJobXYZ Status: ' + a.Status);
 mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems +
  ' batches with '+ a.NumberOfErrors + ' failures. ExtendedStatus: ' + a.ExtendedStatus);
  
 Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}

 
Best Answer chosen by JSchneider
Amit Chaudhary 8Amit Chaudhary 8
Yes you can all another batch job from finish method like below code
global class batchProAssetBuilder implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String myProduct = 'xyz';
        String query = 'SELECT Id,Run_Asset_Builder_Pro__c FROM Account WHERE PIN_Code__c != null AND Product__c = :myProduct';
        return Database.getQueryLocator(query);
    }
   
    global void execute(Database.BatchableContext BC, List<Account> scope) {
         for(Account a : scope)
         {
             a.Run_Asset_Builder_Pro__c = true;            
         }
         update scope;
    }   
    
global void finish(Database.BatchableContext BC){

 // Get the AsyncApexJob that represents the Batch job using the Id from the BatchableContext
 AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed,
  TotalJobItems, CreatedBy.Email, ExtendedStatus
  from AsyncApexJob where Id = :BC.getJobId()];
 
 // Email the Batch Job's submitter that the Job is finished.
 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
 String[] toAddresses = new String[] {a.CreatedBy.Email};
 mail.setToAddresses(toAddresses);
 mail.setSubject('BatchJobXYZ Status: ' + a.Status);
 mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems +
  ' batches with '+ a.NumberOfErrors + ' failures. ExtendedStatus: ' + a.ExtendedStatus);
  
 Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

	NewBatchjob obj = new newBatchJob();
	Database.executeBatch(obj);
 
 }
}

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm

Monitoring a Batch

You can monitor a Bulk API batch in Salesforce.
To track the status of bulk data load jobs and their associated batches, from Setup, click Monitoring | Bulk Data Load Jobs orJobs | Bulk Data Load Jobs. Click on the Job ID to view the job detail page.

Please read below post for same issue
https://help.salesforce.com/apex/HTViewSolution?id=000182449

Description
- Batch Apex can have 5 concurrent (simultaneous) jobs running in parallel.
- That is, explicitly, the number of Batch Apex jobs whose status in the AsyncApexJob table are 'Processing' or 'Preparing'.
- A job is not executing when in Queued or any other status.
- Scheduling more than 5 Batch Apex jobs returns the error "Attempted to schedule too many concurrent batch jobs in this org"
- You may sometimes receive a Developer script exception e-mail when this limit is reached, but not always. (This is also by design).
- You may attempt to use the following code sample to avoid encountering this limit, particularly if the batch is executed in a scheduled class. 
//check if there are 5 active batch jobs
//In some cases, might need to add "Status='Queued' " to the criteria
if ([SELECT count() FROM AsyncApexJob WHERE JobType='BatchApex' AND (Status = 'Processing' OR Status = 'Preparing')] < 5){ 
   Database.executeBatch(batchClassInstance);
} else {
   //schedule this same schedulable class again in 30 mins
   nameOfYourSchedulableClass sc = new nameOfYourSchedulableClass();
   Datetime dt = Datetime.now() + (0.024305); // i.e. 30 mins
   String timeForScheduler = dt.format('s m H d M \'?\' yyyy');
   Id schedId = System.Schedule('MatrixRetry'+timeForScheduler,timeForScheduler,sc);
}



Please let us know if this will help you.

Thanks
Amit Chaudhary

All Answers

Himanshu ParasharHimanshu Parashar
Hi J,

You will call another batch from your finish method after line 31
 
BatchName bc = new Batchname();
Database.executeBatch(bcOpp);

Thanks,
Himanshu
Amit Chaudhary 8Amit Chaudhary 8
Yes you can all another batch job from finish method like below code
global class batchProAssetBuilder implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String myProduct = 'xyz';
        String query = 'SELECT Id,Run_Asset_Builder_Pro__c FROM Account WHERE PIN_Code__c != null AND Product__c = :myProduct';
        return Database.getQueryLocator(query);
    }
   
    global void execute(Database.BatchableContext BC, List<Account> scope) {
         for(Account a : scope)
         {
             a.Run_Asset_Builder_Pro__c = true;            
         }
         update scope;
    }   
    
global void finish(Database.BatchableContext BC){

 // Get the AsyncApexJob that represents the Batch job using the Id from the BatchableContext
 AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed,
  TotalJobItems, CreatedBy.Email, ExtendedStatus
  from AsyncApexJob where Id = :BC.getJobId()];
 
 // Email the Batch Job's submitter that the Job is finished.
 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
 String[] toAddresses = new String[] {a.CreatedBy.Email};
 mail.setToAddresses(toAddresses);
 mail.setSubject('BatchJobXYZ Status: ' + a.Status);
 mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems +
  ' batches with '+ a.NumberOfErrors + ' failures. ExtendedStatus: ' + a.ExtendedStatus);
  
 Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

	NewBatchjob obj = new newBatchJob();
	Database.executeBatch(obj);
 
 }
}

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm

Monitoring a Batch

You can monitor a Bulk API batch in Salesforce.
To track the status of bulk data load jobs and their associated batches, from Setup, click Monitoring | Bulk Data Load Jobs orJobs | Bulk Data Load Jobs. Click on the Job ID to view the job detail page.

Please read below post for same issue
https://help.salesforce.com/apex/HTViewSolution?id=000182449

Description
- Batch Apex can have 5 concurrent (simultaneous) jobs running in parallel.
- That is, explicitly, the number of Batch Apex jobs whose status in the AsyncApexJob table are 'Processing' or 'Preparing'.
- A job is not executing when in Queued or any other status.
- Scheduling more than 5 Batch Apex jobs returns the error "Attempted to schedule too many concurrent batch jobs in this org"
- You may sometimes receive a Developer script exception e-mail when this limit is reached, but not always. (This is also by design).
- You may attempt to use the following code sample to avoid encountering this limit, particularly if the batch is executed in a scheduled class. 
//check if there are 5 active batch jobs
//In some cases, might need to add "Status='Queued' " to the criteria
if ([SELECT count() FROM AsyncApexJob WHERE JobType='BatchApex' AND (Status = 'Processing' OR Status = 'Preparing')] < 5){ 
   Database.executeBatch(batchClassInstance);
} else {
   //schedule this same schedulable class again in 30 mins
   nameOfYourSchedulableClass sc = new nameOfYourSchedulableClass();
   Datetime dt = Datetime.now() + (0.024305); // i.e. 30 mins
   String timeForScheduler = dt.format('s m H d M \'?\' yyyy');
   Id schedId = System.Schedule('MatrixRetry'+timeForScheduler,timeForScheduler,sc);
}



Please let us know if this will help you.

Thanks
Amit Chaudhary
This was selected as the best answer