0

In the trailhead lesson "Use Batch Apex" the final line states:

Use extreme care if you are planning to invoke a batch job from a trigger. You must be able to guarantee that the trigger won't add more batch jobs than the limit.

As far as I can see, the limit for concurrent batch processes is 5.

However when I run the following code in order to try and run more than 5 batch processes concurrently, it appears to automatically queue jobs so that the max number running at any time is 5. So - my question - what do you have to do to add more batch jobs than the limit in a trigger and break it?

public class BatchTest {

public static void triggerTest(){
    List<String> stringList = new List<String>{'hello'};
    for(integer i = 0; i < 8; i++){
        Integer runningBatchJobs = [SELECT count() FROM AsyncApexJob WHERE JobType = 'BatchApex' AND status IN ('Queued', 'Processing', 'Preparing')];
        BatchTestBatch batchObject = new BatchTestBatch(stringList);
        Id batchId = Database.executeBatch(batchObject, 1);        
    }   
} }

batchClass :

global class  BatchTestBatch implements Database.Batchable<String>{
private List<String> idList;

public BatchTestBatch(List<String> newIdList){
    idList = newIdList;
}
global Iterable<String> start(Database.BatchableContext bc){
    return idList;
}
global void execute(Database.BatchableContext bc, List<String> scope){
    for(integer i = 0; i < 1; i++){
        test__c[] myTest = [SELECT name FROM test__c]; 
    }
    Integer runningBatchJobs = [SELECT count() FROM AsyncApexJob WHERE JobType = 'BatchApex' AND status IN ('Queued', 'Processing', 'Preparing')];
    System.debug(runningBatchJobs);
    System.debug('hi');
}
global void finish(Database.BatchableContext bc){
    System.debug(' finished');
}}
2

There is now also the Flex Queue that allows up to 100 extra jobs to be submitted and kept in a holding status until one of the 5 concurrent slots is available.

So to "break it" you need to add 5 + 100 + 1 jobs in your test.

2

Use extreme care if you are planning to invoke a batch job from a trigger. You must be able to guarantee that the trigger won't add more batch jobs than the limit

Implies the daily AsyncApexLimit for Jobs like future,queuabale,scheduler and batch. You can only have 250K a day, if you add more they would be denied.

enter image description here

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_gov_limits.htm

1
  • 1
    Plus, each batch will use at least 3 async limits if even one value is returned from start.
    – sfdcfox
    Nov 5 '18 at 13:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.