+ Start a Discussion

Calling batch apex from batch apex

With Winter '13 batch apex can call another batch apex (or itself) from the finish() method. E.g.


global void finish(Database.BatchableContext BC){
  Database.executeBatch(new MyBatch());

I'm noticing that in this scenario (i.e. when a batch keeps running itself again) I get 2 records in the AsyncApexJob table/object for the same MyBatch apex class: 1 record with status 'Processing' and the 2d with status 'Queued'.



1. Is this expected? Shouldn't the first execution of the batch completely stop before the second one gets queued?

2. If above is the expected behavior, at the point of time when there are 2 records - I assume they count  against the limit of having 5 active/queued batch jobs - true?




1) A batch doesn't show as completed until some time after the status moves from 'Processing' to 'Completed', while the next job would indeed be 'Queued', since the previous one is still processing.

2) I haven't personally tried to attain this limit, but it's reasonable to assume that a batch that is finalizing and queues a new batch that would exceed the limit will fail. I will see if I can figure out an easy way to test this programmatically.


sfdcfox, thanks for an informative answer!


With this behavior, the same batch apex may (to be confirmed) consume 2 slots out of 5 allotted, with one instance being 'Queued' and second 'Processing'. If that is true, I'm thinking of using the "old" approach of calling an 'Apex Scheduler' aka 'Scheduled Apex' to run the next batch in 5 or 10 minutes to make sure the executions are completely separated from the limits standpoint.