[SalesForce] Calling another batch from the execute method of another 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.

Best Answer

No, you can't execute a separate batch anywhere other than the finish method. However, you are allowed a single System.enqueueJob call that you could use to process the data using a Queueable class. This queueable class can chain itself indefinitely (in production) to use as much CPU time as it pleases (but there will be delays between each successive chain to limit resource usage).

Related Topic