Deleting Stuck Jobs Via Salesforce 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);
}
Sharing is Caring

Brian is a software architect and technology leader living in Niagara Falls with 13+ years of development experience. He is passionate about automation, business process re-engineering, and building a better tomorrow.

Brian is a proud father of four: two boys, and two girls and has been happily married to Crystal for more than ten years. From time to time, Brian may post about his faith, his family, and definitely about technology.

2 Comments

  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’ ?

    • 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.

Comments are closed.