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
ShamilShamil 

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'.

 

Questions:

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?

 

Thanks!

sfdcfoxsfdcfox

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.

ShamilShamil

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.