How to know how many records where sucess and failed in batch class?

Lets say you want to send an email to some user on end of batch class that how many records where successfully executed and how many were failed to be executing.

Its very simply to do if you know the Object used to store data related to Async jobs.

There is called Standard object named AsyncApexJob which store information of jobs runs.

You can query on AsyncApexJob object to get record of currently run batch by its Batch id in finish method.

Fields to be Used:

JobItemsProcessed: Number of job items processed. Label is Batches Processed.
NumberOfErrors: Total number of batches with a failure. A batch is considered transactional, so any unhandled exceptions constitute an entire failure of the batch. Label is Failures.


global void finish(Database.BatchableContext BC) {
 
 
//Below code will fetch the job Id

 AsyncApexJob a = [Select a.TotalJobItems, a.Status, a.NumberOfErrors, a.JobType, a.JobItemsProcessed, a.ExtendedStatus, a.CreatedById, a.CompletedDate From AsyncApexJob a WHERE id = :BC.getJobId()];             

}
                            
you can use above code to send mail with details of job.

Hope you will find it useful.

For more details of Object visit:
Here

No comments:

Post a Comment