Pages

Friday, March 9, 2012

Salesforce - Sending a notification when Batch Apex completes

When an apex batch job completes I've found it useful to send an email to the user who initiated the process. This can help expose issues where the batch job is failing and lets them know it is complete.

In your apex class that implements Database.Batchable<:sObject>:

global void finish(Database.BatchableContext BC){

 // Get the AsyncApexJob that represents the Batch job using the Id from the BatchableContext
 AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed,
  TotalJobItems, CreatedBy.Email, ExtendedStatus
  from AsyncApexJob where Id = :BC.getJobId()];
 
 // Email the Batch Job's submitter that the Job is finished.
 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
 String[] toAddresses = new String[] {a.CreatedBy.Email};
 mail.setToAddresses(toAddresses);
 mail.setSubject('BatchJobXYZ Status: ' + a.Status);
 mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems +
  ' batches with '+ a.NumberOfErrors + ' failures. ExtendedStatus: ' + a.ExtendedStatus);
  
 Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}

Full credit really needs to go to Sam Arjmandi - Utilizing the Power of Batch Apex and Async Operations where I picked the base of this up from.

3 comments:

  1. Hi Daniel,

    This is good. How to send email only when the job fails. I dont want to send email everytime either success or failure.
    I want only when the job fails.

    Regards,

    ReplyDelete
    Replies
    1. Hi Jagan,

      Check the AsyncApexJob.Status. You could send the email only if it is 'Failed'. See https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_asyncapexjob.htm

      Delete
  2. Thanks it will help me :D
    Regards,
    Julie.

    ReplyDelete