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);
    }  
}

Answer

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

E.g.

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.setToAddresses(toAddresses);
        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);

    }
} 

Attribution
Source : Link , Question Author : Mahmood , Answer Author : Daniel Ballinger

Leave a Comment