Simple Batch Job Status email in batch’s finish method in Salesforce

Simple Batch Job Status email in batch’s finish method in Salesforce

Sample Code:

  1. global class SampleBatch Implements Database.Batchable <sObject> {  
  2.           
  3.     global Database.queryLocator start( Database.BatchableContext bc ) {  
  4.       
  5.         String SOQL = ‘SELECT Id, Name FROM Account LIMIT 1’;  
  6.         return Database.getQueryLocator(SOQL);  
  7.           
  8.     }  
  9.       
  10.     global void execute( Database.BatchableContext bc, List < sObject > scope ) {  
  11.           
  12.     }  
  13.       
  14.     global void finish( Database.BatchableContext bc ) {  
  15.           
  16.         AsyncApexJob a = [ SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedById  
  17.                              FROM AsyncApexJob  
  18.                             WHERE Id =: bc.getJobId() ];  
  19.         Messaging.SingleEmailMessage batchEmail = new Messaging.SingleEmailMessage();  
  20.         batchEmail.setTargetObjectId( a.CreatedById );  
  21.         batchEmail.setSubject( ‘Batch ‘ + a.Status );  
  22.         batchEmail.setPlainTextBody( ‘Jobs processed ‘ + a.JobItemsProcessed + ‘ with ‘+ a.NumberOfErrors + ‘ failures.’ );  
  23.         batchEmail.setSaveAsActivity( false );  
  24.         Messaging.sendEmail( new Messaging.SingleEmailMessage[] {batchEmail} );  
  25.           
  26.     }  
  27.       
  28. }  

Output:

Leave a Reply