Batch Apex is a powerful tool that can be used to do all sorts of cool stuff on the Salesforce platform.  Batch Apex is typically used to perform larger operations that would normally be restricted by governor limits.  It allows you to break that larger operation up into smaller bite-size chunks that are easier to deal with.

Since batch jobs are meant to deal with one query and processing records from that query, there may be times when you want to spin off another batch job when one is complete to finish your processing.  An example of when you might want to do this would be if you needed to perform a batch job to delete thousands of records but once those records were deleted, you need to create thousands of records based off of another query or object.

Starting a batch job from a batch job is fairly straightforward.  The key is placement of the code that actually starts the new batch.  The code that starts the new batch needs to be placed in the finish method of the initial batch.

globalvoid finish(Database.BatchableContext BC){
    //Add your start code for the other batch job here
    Database.executeBatch(new YourOtherBatchClass());

That’s pretty much it.  Calling executeBatch from the finish method of one batch job will kick off the new batch job.  There are a lot of fun things you can do with this.  One thing I have done has been to create a recursive batch job that calls itself.  If you are ever in a situation where you need to call a batch from a batch.


Leave a Comment

Your email address will not be published. Required fields are marked *

Select Language »