Showing posts with label Batch apex. Show all posts
Showing posts with label Batch apex. Show all posts

Thursday, January 9, 2020

How to abort the Scheduled batch job using Apex in Salesforce

The Scheduled batch job information internally stored in CornTrigger object in salesforce.

Ex:  let as assume you scheduled the batch job using System.schedule(jobName, cronExp, schedulable) method it returns the CornTrigger record Id.

String strCornExp = '0 38 * * * ?';
Id cornId = System.schedule('Test Job', strCornExp, new ScheduleJob());

Query the information based on record Id and use the System.abortJob(cornTriggerId); method to abort the scheduled job.

CronTrigger obj = [SELECT Id, CronJobDetail.Name, CronJobDetail.Id,State FROM CronTrigger where CronJobDetail.Name = 'Test Job'];
System.abortJob(obj.Id);

Tuesday, April 23, 2019

How to get all batch apex class names in org?

This post explains how to get all apex batch class names list in Org.

Example:

list<ApexClass> lstApexClasses = [SELECT Id, Name, ApiVersion, Body FROM ApexClass where NamespacePrefix = null];
for(ApexClass iterator : lstApexClasses) {
    if(iterator.Body.contains('Database.Batchable')) {
        system.debug('Batch Class Name ====> '+iterator.Name+' Api Version ====> '+iterator.ApiVersion);
    }
}

Result

Wednesday, April 17, 2019

How to get the batch apex class total run time in minutes using apex

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.

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