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
Neema Gudur 8Neema Gudur 8 

Calling a batch from the execute method of a running batch

Is it possible to initiate another batch from the Execute method of a running batch?
My requirement:
Users charge time to Timecards. At the end of the week I have a group of timecards (Timecard Header records) where time is charged to place holder projects. These place holder projects have child projects that are Billable projects. The time charged to these place holder projects should be distributed to all the active milestones of these child projects. Currently, I have a future method that takes the time from this timecard with the place holder project and distributes it the active milestones of the child projects by creating time card Header record for each of these active milestone/project combination. We are running into CPU time limit error when a place holder project has large no. of child projects.
In order to get around this problem I chose to implement this using batch apex. The idea is to have one batch apex batch1 to process these place holder timecards in batches of 1. Then in the Execute method of batch1, if the child project count > 50 then initiate batch2 from the Execute method to process 10 child projects at a time.
 
Navees Ahmed 8Navees Ahmed 8
You cannot call batch from execute method, but you can call that in finish method. I had same use case and I had called next batch to process child records in finish method. 
Neema Gudur 8Neema Gudur 8
Hi Navees, Thank you. Can you please elaborate. I am trying to come up with a design to get around this. What was your requirement? 
Navees Ahmed 8Navees Ahmed 8
You can create a static variable to hold number of records and in finish if that count is greater than e.g 50 then execute another batch

 global void finish(Database.BatchableContext BC) {
   if(totalrecords>50)
   {
       BatchClassName batch2 = new BatchClassName();
       ID batchprocessid = Database.executeBatch(batch2);
   }
}
Neema Gudur 8Neema Gudur 8
I don't see how this could be a solution in my case. Each place holder timecard has to be distributed to child projects. For example I have 10 timecards. The first 5 have 10 child projects but timecard 6, 8 and 10 have 60 child projects. I need to process the child projects per timecard. 
James (CloudAnswers)James (CloudAnswers)
With that few records, you probably don't need a batch.  The govorner limits get a bad name for being low, but you should be able to use nested queries and maybe something else to reduce the need for so many batches.  Otherwise, you can use Queuable:  https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_queueing_jobs.htm