How to fix System.LimitException: Attempted to schedule too many concurrent batch jobs in this org (limit is 5) issue?

How to fix System.LimitException: Attempted to schedule too many concurrent batch jobs in this org (limit is 5) issue?

To fix System.LimitException: Attempted to schedule too many concurrent batch jobs in this org (limit is 5) issue, instead of calling Database.execute method in test class, call the Scheduler class in the test method. If the batch class doesn’t contain Scheduler class, create a scheduler class for it.

Sample Batch Class:

global class AccountUpdateBatch Implements Database.Batchable <sObject> {
    Set<Id> acctIds = new Set<Id>();
    global AccountUpdateBatch(Set<Id> acctIds) {
        this.acctIds = acctIds;
    }
    
    global Database.queryLocator start(Database.BatchableContext bc) {
        String SOQL = ‘SELECT Id, Description FROM Account’;
        if(acctIds != null) {
            SOQL += ‘ WHERE Id IN: acctIds’;
        }
        return Database.getQueryLocator(SOQL);
    }


    global void execute(Database.BatchableContext bc, List<Account> listAccount) {
        for(Account acct : listAccount) {
            acct.Description = ‘Testing’;
        }
        update listAccount;
    }


    global void finish(Database.BatchableContext bc) {
    }
}

Sample Scheduler class:

global class AccountUpdateBatchScheduler Implements Schedulable {
    AccountUpdateBatch objAcctUpdate;
    global AccountUpdateBatchScheduler(AccountUpdateBatch objAcctUpdate) {
        this.objAcctUpdate = objAcctUpdate;
    }
    
    global void execute(SchedulableContext sc) {
        AccountUpdateBatch obj = new AccountUpdateBatch(null);
        if(objAcctUpdate != null) {
            Database.executeBatch(objAcctUpdate);
        } else {
            Database.executeBatch(obj);
        }
    }
}

Test class for the batch class to avoid concurrent issue:

@istest
private with sharing class AccountUpdateBatchTest {
    static testmethod void testSample() {
        Account acct = new Account(Name = ‘Test’);
        insert acct;
        AccountUpdateBatch obj = new AccountUpdateBatch(new Set<Id> {acct.Id});
        Test.startTest();
        Datetime dt = Datetime.now().addMinutes(1);
        String CRON_EXP = ‘0 ‘+ dt.minute() + ‘ * ‘ + dt.day() + ‘ ‘ + dt.month() + ‘ ? ‘ + dt.year();
        String jobId = System.schedule(‘Sample_Heading’, CRON_EXP, new AccountUpdateBatchScheduler(obj) );   
        Test.stopTest();
    }
}

Cheers!!!

Leave a Reply