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
DbjensenDbjensen 

Simple Class - Apex CPU time limit exceeded

Hello - I have small class that looks for an existing lead that matches a newly inserted lead. If a matching lead is found, it checks a box called Resubmitted. If I dataload any more than 10 records, I get a CPU time limit error. What do I need to do to fix this code so I load leads in bulk? 

Class:
  1. public class ResubmittedLead {
  2.     public static void resubmittedLead(List<Lead> reLead){
  3.         List<Lead> leadList = new List<Lead>();
  4.         //Lead Maps
  5.         Map<String, String> mapOfLeadId = new Map<String, String>();      
  6.         for (Lead ld : reLead){   
  7.             mapOfLeadId.put(ld.LastNameStreetAndZipCode__c, ld.Status);
  8.         }
  9.        //Search for existing lead
  10.         for(Lead existingLd : [Select Id, Status FROM Lead WHERE LastNameStreetAndZipCode__c IN :mapOfLeadId.keySet()
  11.                               AND Duplicate__c = false]){
  12.             existingLd.Resubmitted__c = true;
  13.             leadList.add(existingLd);    
  14.         }
  15.         update leadList;
  16.     }
Trigger:
  1. if (Trigger.IsAfter) {
  2.                 if (Trigger.isInsert){
  3.                     for(Lead ld:Trigger.new){
  4.                         if(ld.Duplicate__c == true){
  5.                             ResubmittedLead.resubmittedLead(Trigger.new);
  6.                         }
  7.                     }
  8.                }
  9.           }
Best Answer chosen by Dbjensen
Raj VakatiRaj Vakati
Change your trigger as below
 
if (Trigger.IsAfter) {
                if (Trigger.isInsert){
					Set<Lead> ids = new Set<Lead>();
                    for(Lead ld:Trigger.new){
                        if(ld.Duplicate__c == true){
							ids.add(ld);
                            //ResubmittedLead.resubmittedLead(Trigger.new);
                        }
                    }
					
					ResubmittedLead.resubmittedLead(ids)
					
               }
          }

 

All Answers

Raj VakatiRaj Vakati
Change your trigger as below
 
if (Trigger.IsAfter) {
                if (Trigger.isInsert){
					Set<Lead> ids = new Set<Lead>();
                    for(Lead ld:Trigger.new){
                        if(ld.Duplicate__c == true){
							ids.add(ld);
                            //ResubmittedLead.resubmittedLead(Trigger.new);
                        }
                    }
					
					ResubmittedLead.resubmittedLead(ids)
					
               }
          }

 
This was selected as the best answer
DbjensenDbjensen
That did it. Thanks so much. I really appreciate this.