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