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
Austin GutzAustin Gutz 

CPU time limit - Help

I found a very basic Apex class to update a custom object and have it scheduled to run nightly. It was working just fine for a few days but now I'm getting a CPU time limit error.

Would it help to only list the records that need updating? If yes, what do I need to modify in the class to do so?

I'd like to only update records were Field1__c != Field__c2
global class DailyOpenInvoiceUpdate implements Schedulable {

    global void execute(SchedulableContext ctx) {
        List<Open_Invoices__c> lList = [Select Id, Name from Open_Invoices__c];
        
      update lList;
    
    }
}

 
Amit Chaudhary 8Amit Chaudhary 8
Please add the filter in your query to reduce the number of records.
Austin GutzAustin Gutz
Hi Amit,

My question is how to do that? Is it as simple as adding:
Select Id, Name from Open_Invoices__c where Field1__c != Field2__c

 
Amit Chaudhary 8Amit Chaudhary 8
i dnt think so you can do that . You need to update your code like below
global class DailyOpenInvoiceUpdate implements Schedulable {

    global void execute(SchedulableContext ctx) {
	
		List<Open_Invoices__c> lstINVToUpdate = new List<Open_Invoices__c>();
        List<Open_Invoices__c> lList = [Select Id, Name,Field1__c ,Field2__c  from Open_Invoices__c];
        for(Open_Invoices__c inv : lList){
			if(inv.Field1__c != inv.Field2__c){
				lstINVToUpdate.add(inv);
			}
		}
		
		if(lstINVToUpdate.size() > 0){
			update lstINVToUpdate;
		}
    }
}