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
Mamadou Diallo 14Mamadou Diallo 14 

Apex CPU time limit exceeded (FATAL_ERROR|System.LimitException)

Hello,

I'm merging Account triggers into one but I'm getting Apex CPU time limit exceeded. 

Here is the Apex Class
trigger AccountTrigger on Account (after insert, after update, before insert, before update) {
     AccountTriggerHandler  handler = new AccountTriggerHandler (Trigger.oldMap, Trigger.newMap);

               if((Trigger.isAfter && Trigger.isUpdate) || (Trigger.isAfter && Trigger.isInsert)){
                handler.acctSegmentRules();
           
      }        
}

And the trigger
public class AccountTriggerHandler {
    Map<Id, Account> oldAccts;
    Map<Id, Account> newAccts;
    
    public AccountTriggerHandler (Map<Id, Account> oldTriggerAccts, 
    Map<Id, Account> newTriggerAccts){
        oldAccts = oldTriggerAccts;
        newAccts = newTriggerAccts;
    }

/ Account Segment Rules
    public void acctSegmentRules(){
   // Set of Owners Ids
    Set<Id> ownerIds = new Set<Id>();
    //Create a list of accounts to update 
    List<Account> acctsListToUpdate = new List<Account>(); 
    if(newAccts != null){
		for (Account acc : newAccts.values()) {
            ownerIds.add(acc.ownerId);
        }
    }   
    String accName;      
    
    //Check if the trigger is running again
    if(RecursiveTriggerHandler.runOnce()){
        
        for (Account a : newAccts.values()) {
         //Query the owner role description
            // Check if the account ID is not null 
            // to avoid "referencing null object" error       
            if(a != NULL  && a.ID !=NULL){
          
				// create a placeholder account a1    
				 Account a1  = new Account(Id = a.Id, Name = a.Name, Original_ID__c = a.Original_ID__c, OwnerId = a.OwnerId);
				//Check if a1 is not not null and name is not empty
				if(a1 != NULL && a1.Name != NULL){
					accName = a1.Name;
				}
				//Set the condition for AAA & BBB
				Boolean result1 = accName.contains('AAA');
				Boolean result2 = accName.contains('BBB');  
            
                if(a1.Original_ID__c == '895010423'&& result1 == FALSE && result2 == FALSE ){
                        //Change the SubGroup to Other Dealer    
                       a1.SubGroup__c = 'Other Dealer';
                        // add a1 to the list of accounts to update     
                        acctsListToUpdate.add(a1);  
                       } else    
                        // Check if name contains AAA
                        if(result1 == TRUE && result2 == FALSE && a1.Original_ID__c != '895010423'){
                             //Change the Segment to AAA    
                            a1.SubGroup__c = 'Dealer - AAA';
                              //  add a1 to the list of accounts to update     
                              acctsListToUpdate.add(a1);  
                            }else if( //Check if name contains BBB
                            result2 == TRUE && result1 == FALSE && a1.Original_ID__c != '895010423'){
                             //Change the Segment to BBB   
                             a1.SubGroup__c = 'Dealer - BBB';
                              //  add a1 to the list of accounts to update     
                              acctsListToUpdate.add(a1);  
                            }else if(result2 == FALSE && result1 == FALSE && a1.Original_ID__c != '895010423'){
                                 
                               Map<Id,User> userMap = new Map<Id,User>([Select Id,Employee_Function__c From User where Id IN :ownerIds]);
                                if(userMap.containskey(a1.OwnerId)) {
                                    if( userMap.get(a1.OwnerId).Employee_Function__c=='Operations'){
                                        a1.SubGroup__c='Other';
                                        acctsListToUpdate.add(a1);  
                                    }
                                    else
                                    {
                                        a1.SubGroup__c=userMap.get(a1.OwnerId).Employee_Function__c;
                                        acctsListToUpdate.add(a1);  
                                    }
                                }      
                            }  
                } 
                //Bulkify the update    
                if(acctsListToUpdate.size()>0){ 
                    update acctsListToUpdate; 
                }            
        }     
    } 
}
Thank you for your help.
Rahul KumarRahul Kumar (Salesforce Developers) 

Hi Mamadou Diallo,

Here is an article from Salesforce on how you can address this Apex CPU time limit exceeded error with best practices.
  •  https://help.salesforce.com/apex/HTViewSolution?id=000232681&language=en_US (http:// https://help.salesforce.com/apex/HTViewSolution?id=000232681&language=en_US)​​
  • Resolution: We only count events that require application server CPU use. There are some things that use the app server CPU that we don't count, which are things beyond your control as a programmer. For example, the time spent in the database retrieving records won't count, nor will time spent waiting for a call out to return. You don’t control when your code needs compilation, so we don’t count that.
     
    We'll count almost everything else that happens on the app server, including declarative actions. If DML in your code encounters a validation rule with a formula, we'll count the time spent evaluating that formula. CPU time is calculated for all executions on the Salesforce application servers occurring in one Apex transaction—for the executing Apex code, and any processes that are called from this code, such as package code and workflows. CPU time is private for a transaction and is isolated from other transactions. Operations that don’t consume application server CPU time aren’t counted toward CPU time
.  I hope it will be helpful.

Please mark it as best answer if the information is informative.

Best Regards
Rahul Kumar