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

Adding a red asterisk to required fields using label in LWC

The Developer Console didn't set the DEVELOPER_LOG trace flag on your user. Having an active trace flag triggers debug logging. You have 1,978 MB of the maximum 1,000 MB of debug logs. Before you can edit trace flags, delete some debug logs.

Troubleshoot 'System.LimitException: Batchable instance is too big' error