August 18, 2021

System.LimitException: Too many queueable jobs added to the queue

Reference Article - https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_queueing_jobs.htm

Limits.getQueueableJobs(): getQueueableJobs() Returns the number of queueable jobs that have been added to the queue per transaction. A queueable job corresponds to a class that implements the Queueable interface.
 
You can add up to 50 jobs to the queue with System.enqueueJob in a single transaction. 

When chaining jobs with System.enqueueJob, you can add only one job from an executing job. Only one child job can exist for each parent queueable job. Starting multiple child jobs from the same queueable job isn’t supported.

System.LimitException: Too many queueable jobs added to the queue: 2
You can only create one queueable job within a batch execution.

Sample code to reproduce:
Queueable Interface:
public class SampleQueueable implements Queueable {

    public void execute(QueueableContext context) {
    
        system.debug( 'Inside Queueable Interface' );
        
    }
    
}
 
Batch Apex:
global class SampleBatch implements Database.Batchable<sObject> {
    
    global Database.QueryLocator start( Database.BatchableContext BC ) {
    
        String strSOQL = 'SELECT Id FROM Account LIMIT 2';
        return Database.getQueryLocator( strSOQL );
        
    }
    
    global void execute( Database.BatchableContext BC, List< Account > listAccounts ) {
    
        for ( Account acc : listAccounts ) {
            System.enqueueJob( new SampleQueueable() );
        }
        
    }   
    
    global void finish( Database.BatchableContext BC ) {
    }
    
}

Code to execute to reproduce the issue:
Database.executeBatch( new SampleBatch() );

2 comments:

  1. Good example to understand the concept.

    If i execute the same snippet with scope 1, will not face this issue right.

    Database.executeBatch( new SampleBatch(),1);

    ReplyDelete