Find Apex batch status programmatically

I have a batch class, I need to email and run another batch in the ‘Finish’ method of batch ONLY IF the batch ran successfully. I would like to have batch status in the finish method (like the batch status as we see in the apex jobs), so that I could check for it and if it was completed then finish() should perform necessary tasks.

global class x70RecordExtract implements Database.Batchable<SObject>, Database.Stateful {

    global Database.QueryLocator start(Database.BatchableContext bc) {

       // query data
    global void execute(Database.BatchableContext bc, SObject[] scope) {
        // 1. build data (in my case it is CSV) 
        // 2. delete scope
    global void finish(Database.batchablecontext bc) {
        // Check batch status - IF COMPLETED then 
        // 1. Send Email (CSV created in execute method)

        // 2. database.executebatch(new chain_batch(),200);


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can check the AsyncApexJob.Status using the JobId from the Database.BatchableContext.


global void finish(Database.batchablecontext bc) {

    // Check batch status - IF COMPLETED then 
    AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed,
        TotalJobItems, CreatedBy.Email, ExtendedStatus
        from AsyncApexJob where Id = :bc.getJobId()];        

    if(a.Status == 'Completed') {

        // 1. Send Email (CSV created in execute method)

        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        // Send the email to the job submitter
        String[] toAddresses = new String[] {a.CreatedBy.Email};
        mail.setSenderDisplayName('Batch Processing');
        mail.setSubject('x70RecordExtract  Status: ' + a.Status);
            mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems +
            ' batches with '+ a.NumberOfErrors + ' failures. ExtendedStatus: ' + a.ExtendedStatus);

        // Add your attachment to the email.

        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

        // 2. database.executebatch(new chain_batch(),200);


All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x