How can developers programmatically monitor and reorder jobs sitting in the Asynchronous Apex Flex Queue?
Answer
Basics: Jobs waiting in the Flex Queue are processed in order. If an urgent job is stuck behind a big one, you can move it forward without aborting anything.
How it works:
- Find Holding jobs:
SELECT Id, ApexClass.Name FROM AsyncApexJob WHERE Status = 'Holding'. - Call
FlexQueue.moveJobToFront(jobId),moveBeforeJob(jobToMove, jobInQueue),moveAfterJob(jobToMove, jobInQueue)ormoveJobToEnd(jobId). - Each returns a Boolean for success.
- The platform starts jobs from the front as slots free.
Advanced / deep dive: Only jobs with status Holding can be moved. The FlexQueueItem object exposes AsyncApexJobId, JobType and JobPosition for reporting. The Apex Flex Queue page in Setup offers drag and drop. For automated prioritization, a monitoring scheduled job can scan the queue and move jobs of a critical class to the front. Be careful, because constantly promoting jobs starves others. In tests, Test.enqueueBatchJobs(n) fills the Flex Queue with dummy jobs and Test.getFlexQueueOrder() returns the order, letting you verify reordering logic.
Code / config example:
// Promote the nightly integration batch to the front of the queue
List<AsyncApexJob> held = [
SELECT Id FROM AsyncApexJob
WHERE Status = 'Holding' AND ApexClass.Name = 'NightlyIntegrationBatch'
LIMIT 1
];
if (!held.isEmpty()) {
Boolean ok = FlexQueue.moveJobToFront(held[0].Id);
System.debug('Moved: ' + ok);
}
Hidden gotchas & must-remember points:
System.minFlexQueue,maxFlexQueueandupdateFlexQueueare not real methods.- Only Holding jobs are movable; Queued or Processing are not.