function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Will BoyceWill Boyce 

Help changing class to batch apex?

I have an apex class that I need to change to a batch class because there are too many records being processed.  Any help is greatly apprciated! 

Order_Item__c is the child object in a Master-Detail relationship with the Account object.

The scheduled apex reviews all open Order_Item__c records on Accounts and then if those accounts do not have an open outreach case record for those open order items it should create a case.

global class createAffiliateOutreachCases implements Schedulable {
    global void execute(SchedulableContext ctx) {
        
        // Define outbound string variables for queues
        String outboundAffiliate = [SELECT Id from Group where Name = 'Outreach eConnect Affiliate' and Type = 'Queue' Limit 1].Id;        
        
        Datetime affiliateTime = Datetime.now().addDays(-1);
        
        Set<Id> setAffiliate = new Set<Id>();
        
        Id outreachId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('eConnect Outreach').getRecordTypeId();
        
        // Get Open Affiliate and Member Order
        List<Order_Item__c> affiliateOrders = [SELECT id, CreatedDate, Item_Status__c, Account__r.Id FROM Order_Item__c WHERE (Account__r.Partner_Status__c = 'Affiliate' OR Account__r.Partner_Status__C = 'Member') AND (Item_Status__c = 'AWAITING_APPROVAL' OR Item_Status__c = 'FAILED_TO_COMMUNICATE_VET')];

        for (Order_Item__c o :affiliateOrders) {
            if (o.CreatedDate <= affiliateTime && !setAffiliate.contains(o.Account__r.Id)) {
                setAffiliate.add(o.Account__r.Id);
            }
        }        
        
        List<Account> accsAffil = [SELECT Id FROM Account WHERE Id IN :setAffiliate];
        
        List<Case> opencases = [SELECT Id, Account.Id FROM Case WHERE RecordTypeId = :outreachId AND Status != 'Completed'];
        
        List<Case> NewCases = new List<Case>();
        
        List<Account> hasrecord = new List<Account>();
        
        for (case c: opencases) {
            hasrecord.add(c.Account);
        }
        
        for (account a: accsAffil) {
            if (hasrecord.contains(a) == false){
                Case c = new Case();
                c.Accountid = a.Id;
                c.OwnerId = outboundAffiliate;
                c.Status = 'New';
                c.RecordTypeId = outreachId;
                c.Subject = 'Please Help Client Approve Orders';
                NewCases.add(c);
            }
        }
        if(!NewCases.isEmpty()){
            insert NewCases;
        }
    }
}
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Will Boyce,

Did you try chaning it to batch class or are you still having issue in it ?

Thanks,