12

Is there a way to abort currently running batch job in Salesforce? I tried to run the query below and all it did was remove all jobs from Scheduled Jobs section without stopping the one that is currently running in the background. Please help. I would like to do it without contacting Salesforce support

    List<CronTrigger> jobsToAbort = [select Id from CronTrigger where CronJobDetail.JobType = '7'];
for (CronTrigger job : jobsToAbort) { System.abortJob(job.Id); }

4 Answers 4

25

Please run a SOQL query on AsyncApexJob with Status filter. CronTrigger is used to retrive Scheduled jobs wherein AsyncApexJob returns Apex Jobs (Running, Aborted, Pending, Completed etc.)

SOLUTION:

Use Below Code:-

for ( AsyncApexJob aJob : [ Select id ,Status, ApexClass.Name 
                              from AsyncApexJob where Status!='Aborted' 
                               and Status!='Completed' ] ){

      System.AbortJob(aJob.Id);

}
3
  • 2
    Very useful for killing a job running amok. Thx.
    – abhi
    Jun 28, 2017 at 18:56
  • 1
    This worked great for me, I could kill some jobs by Apex class name. Thanks. May 16, 2018 at 14:14
  • And what if the count returned is more then 150, is there any way to abort the list of jobs in one go preventing 150 DML exception
    – ScoRpion
    Aug 24, 2020 at 14:10
5

Went to SetUp --> Monitoring --> Apex Jobs. There was Abort option :)

2
  • The navigation may have changed since this answer was written, but the page still exists here: Setup -> Monitoring -> Jobs -> Scheduled Jobs
    – dana
    Jul 17, 2017 at 19:25
  • New path is : Setup > Jobs > Apex Jobs or Setup > Jobs > Scheduled Jobs May 16, 2018 at 13:59
0

Note that if you are in Lightning the Setup path has changed from the above:

Environments > Jobs > Apex Jobs
0

In my case, I wanted to abort the "currently running job" from within the batch itself due to an error condition that would prevent any of the following operations to succeed. See example below:

global override void execute(Database.BatchableContext BC, List<SObject> scope) {
  try {
    /** do stuff **/
  } catch (Exception ex) {
    // the finish method isn't called when we abort, so I forced it to be
    finish(BC); 
    // Get current jobId from batch context to pass to the abort method
    System.abortJob(BC.getJobId());
    // Prevent rest of code in execute method from firing by exiting with return statement
    return;
  } 
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .