Run One Apex Batch for two object but remember always prefer to write batch per object.

 Hi Friends,


I have shared one of the concepts in which we have used one apex batch for two objects. but remember it depends based on the condition.

And according to my opinion, always write apex batch class per/each objects.


global class Batchsampledeleterecord implements Database.Batchable<string>, Database.Stateful, Schedulable {
    global boolean bReRun = false; //will be used to determine if batch has to re-run in case there are more that 10K of records
    global Iterable<String> start(Database.BatchableContext bc) {
        return new list<String> { 'custom_object__c', 'custom_object2__c'}; //list of strings with my object names

    }

    global void execute(Database.BatchableContext bc, list<string> lstsObjectName){
        list<sObject> lstDeleteRecords = new list<sObject>();
        for(string strObjectName : lstsObjectName) {
            for(sObject objsObject : database.query('Select Id from ' + strObjectName)) {
                if(lstDeleteRecords.size() < 9998)
                    lstDeleteRecords.add(objsObject);
                else {
                    bReRun = true;
                    break;
                }
            }
        }
        lstDeleteRecords.sort();
        delete lstDeleteRecords;
    }    
    global void finish(Database.BatchableContext bc){
        // Execute any post-processing operations
        if(bReRun) {
            Database.executebatch(new Batchsampledeleterecord());
       }
    }  

    global void execute(SchedulableContext sc) {
        Batchsampledeleterecord b = new Batchsampledeleterecord();
        database.executebatch(b);
    }

}


Comments

Popular posts from this blog

Salesforce Interview Questions-Reports & Dashboards

Difference between Export & Export All in Data Loader

Locking Statements in Salesforce