[SalesForce] Scheduled Apex Class – Too many DML rows: 10001

I'm trying to schedule an apex class to run once every month to reset a number field on all Accounts to 0.

global class updateMonthlyActivityCount Implements Schedulable{
public list<Account> updatedList ;

global void execute(SchedulableContext sc) {
    updateAcc();
}

@future 
public static void updateAcc(){
    List<Account> updatedList = new List<Account>();
    List<Account> accList = [SELECT Id, Monthly_Activity_Count__c FROM Account WHERE Monthly_Activity_Count__c = null OR Monthly_Activity_Count__c > 0];
    for(Account a:accList){
        a.Monthly_Activity_Count__c = 0;
        updatedList.add(a);
    }
        update updatedList;
    }
}

Since this is running on all Accounts, I also have a number of processes / flows on Accounts that get triggered when created / edited, which is what I suspect the issue is by getting the error Too many DML rows: 10001

I also noticed it says First error: Apex CPU time limit exceeded on method updateAcc when I look at the status under Apex Jobs.

Any idea how I can get around this? Thanks!

Best Answer

AJ,

This code should get you going. It allows you to schedule and batch....

global class updateMonthlyActivityCount Implements Schedulable,  Database.Batchable<sObject> {

    global void execute(SchedulableContext sc) {
        Database.executeBatch(this, 200); //You can change the "200" number for anything else
    }

    global Database.QueryLocator start(Database.BatchableContext BC) {
        string query = 'SELECT Id, Monthly_Activity_Count__c FROM Account WHERE Monthly_Activity_Count__c = null OR Monthly_Activity_Count__c > 0';

        return new Database.getQueryLocator(query);

    }

    global void execute(Database.BatchableContext BC, List<sObject> scope) {
        List<Account> accList = (List<Account) scope;

        for(Account a : accList){
            a.Monthly_Activity_Count__c = 0;
        }

        update accList;
    }

    global void finish(Database.BatchableContext BC) {

    }
}
Related Topic