This post explains how to get the batch apex start time, end time and batch apex total run time in minutes.
some times we need to track the running time batch class, this example shows how to track time.
some times we need to track the running time batch class, this example shows how to track time.
Example:
ChangeAccountIndustryBatch.cls
global class ChangeAccountIndustryBatch implements Database.Batchable<sObject>, Database.stateful {
// start method
global Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator('SELECT Id, Name, Industry, Type From Account Where Type = \'Customer - Channel\'');
}
// execute method
global void execute(Database.BatchableContext bc, list<sObject> scope) {
if(scope != null && !scope.isEmpty()) {
list<Account> lstAccsToUpdate = new list<Account>();
for(Account accIterator : (list<Account>)scope) {
accIterator.Industry = 'Banking';
lstAccsToUpdate.add(accIterator);
}
if(!lstAccsToUpdate.isEmpty()) {
Database.update(lstAccsToUpdate, false);
}
}
}
// finish method
global void finish(Database.BatchableContext bc) {
AsyncApexJob objAsyncJob = [SELECT Id, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors, ExtendedStatus, CompletedDate, CreatedDate FROM AsyncApexJob WHERE Id = :bc.getJobId()];
String strSubject = 'ChangeAccountIndustryBatch with id ' + objAsyncJob.Id + ' is completed with ' + objAsyncJob.Status;
// Email Body
String strBatchBody = 'The batch apex job processed ' + objAsyncJob.TotalJobItems + ' batches with ' + objAsyncJob.NumberOfErrors + ' failures.<br/>'
+ 'Start time: <b>' + objAsyncJob.CreatedDate.format('MM/dd/yyyy HH:mm') + '</b><br/>'
+ 'End time: <b>' + objAsyncJob.CompletedDate.format('MM/dd/yyyy HH:mm') + '</b><br/>'
+ 'Time taken in minutes: <b>' + ((Decimal)(objAsyncJob.CompletedDate.getTime() - objAsyncJob.CreatedDate.getTime())/1000/60).setScale(2) + '</b><br/>';
// Single email
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
// Sets the paramaters of the email
email.setSubject(strSubject);
email.setHtmlBody(strBatchBody);
email.setTargetObjectId(UserInfo.getUserId());
email.setSaveAsActivity(false);
// Sends the email
list<Messaging.SendEmailResult> lstEmailResult = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
}
}
Run script from Annoymous window
Database.executeBatch(new ChangeAccountIndustryBatch());
Result
No comments:
Post a Comment