Deleting Stuck Jobs Via Salesforce Apex

Deleting Stuck Jobs Via Apex
Sharing is Caring

Every now and then, I find I get a few jobs that are stuck in the queue which end up causing things like reports to stop being generated or stop pardot from syncing or just causing general chaos.

Note: this no longer works in Salesforce Orgs that have been upgraded past version 38, and apex must have an API version less than 39.

I usually run a very slight variation of the following code through the developer console if there are more than a dozen jobs still in holding. You can go to the developer console by clicking on your picture in the top right corner of Salesforce and then selecting “Developer Console”.

Opening Developer Console

Then choose the Debug menu, and choose “Open Execute Anonymous Window”

for ( AsyncApexJob aJob : [SELECT Id, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors FROM AsyncApexJob Where Status = 'Holding']) {
    system.abortJob(aJob.Id);
}

Note: you should never run this exact apex from the developer console without running the query to see what would be ended. It’s completely possible that you will kill asynchronous apex jobs that need to run.

A very good variation through would only stop jobs that have been queued and waiting for quite some time would be to add the CreatedDate or LastModifiedDate to the query. Like this:

for ( AsyncApexJob aJob : [SELECT Id, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors FROM AsyncApexJob Where Status = 'Holding' AND CreatedDate <= YESTERDAY]) {
    system.abortJob(aJob.Id);
}

Author: Brian Cline

Brian is a programmer living in Niagara Falls with ten years of development experience. He is passionate about automation, business process re-engineering, and gamification. For the last six years or so, he has been working with Salesforce and JavaScript.

Related Posts

Sharing is Caring

2 Responses to “Deleting Stuck Jobs Via Salesforce Apex”

  1. How does this work, in V39.0, you get an error ‘System.StringException: You can’t abort scheduled Apex jobs by calling System.abortJob with an AsyncApexJob ID. Call System.abortJob with the parent CronTrigger ID’ ?

    1. Doesn’t seem like it works in Version 39.

      I think the only way it could work now would be to call it off the CronTrigger object which isn’t really so great.