Reorder Your Batch Jobs in the Flex Queue Programmatically

Apex methods in the new System.FlexQueue class enable you to automate the prioritization of batch jobs in the Apex flex queue. Previously, you could reorder jobs in the flex queue only from the Salesforce user interface. New methods in the System.Test class enable you to enqueue no-operation batch jobs in a test version of your batch queue and flex queue.

You can place up to 100 batch jobs in a holding status for future execution. When system resources become available, the jobs are taken from the top of the Apex flex queue and moved to the batch job queue. Up to five queued or active jobs can be processed simultaneously for each org. When a job is moved out of the flex queue for processing, its status changes from Holding to Queued. Queued jobs are executed when the system is ready to process new jobs.

This example moves a job in the flex queue so that it is executed immediately before the specified job in the queue. To move the job, call the System.FlexQueue.moveBeforeJob() method and pass it both jobs’ IDs.
ID jobToMoveId = System.enqueueJob(new MyQueueableClass());
AsyncApexJob a = [SELECT Id FROM AsyncApexJob WHERE ApexClassId IN
                   (SELECT Id from ApexClass WHERE NamespacePrefix = null
                    AND Name = 'BatchJob')]);
ID jobInQueueId = a.ID;
Boolean isSuccess = FlexQueue.moveBeforeJob(jobToMoveId, jobInQueueId);

Use the two new methods in the System.Test class—enqueueBatchJobs and getFlexQueueOrder—to enqueue and reorder no-operation jobs within the contexts of tests.