Ad Code

✨🎆 Codex 1.0 PLACEMENT READY PROGRAM! 🎆✨

Get 75% Discount Early bird offer CLICK to JOIN CodeX 1.0 click

APEX Asynchronous Operation using APEX Batch and Iterable both

 



global class ApexBatchQueryExample implements Database.Batchable<SObject>{

global Database.QueryLocator start(Database.BatchableContext bc) {

       String data='Indore';

        // Query all active Accounts

        return Database.getQueryLocator(

             

            'SELECT Id, Name, Industry FROM Account WHERE Name = :data'

        );

    }

    global void execute(Database.BatchableContext bc, List<SObject> scope) {

        List<Account> accList = (List<Account>) scope;

        for (Account acc : accList) {

            acc.Industry = 'Technology';  // Example processing

        }

        update accList;

    }

    

    global void finish(Database.BatchableContext bc) {

        System.debug('Batch Completed Successfully!');

    }

    

}





global class ApexIterableExample implements Database.Batchable<Account> {

    // Start returns an Iterable<Account>

    global Iterable<Account> start(Database.BatchableContext bc) {

        return new AccountIterable('Indore');

    }


    // Execute receives typed List<Account>

    global void execute(Database.BatchableContext bc, List<Account> scope) {

        for (Account acc : scope) {

            acc.Industry = 'ssssss';

        }

        update scope;

    }


    global void finish(Database.BatchableContext bc) {

        System.debug('Batch Completed Successfully!');

    }


    // Nested Iterable class (global to ensure visibility)

    global class AccountIterable implements Iterable<Account> {

        private String data;

        global AccountIterable(String data) {

            this.data = data;

        }

        global Iterator<Account> iterator() {

            return new AccountIterator(data);

        }

    }


    // Nested Iterator class (global + correct constructor name)

    global class AccountIterator implements Iterator<Account> {

        private List<Account> accList = new List<Account>();

        private Integer idx = 0;


        global AccountIterator(String data) {

            accList = [SELECT Id, Name, Industry FROM Account WHERE Name = :data];

        }


        global boolean hasNext() {

            return idx < accList.size();

        }


        global Account next() {

            return accList[idx++];

        }

    }

}


Database.executeBatch(new AccountBatchUsingIterable(), 200);

Post a Comment

0 Comments