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
Shawn Reichner 29Shawn Reichner 29 

Apex CPU Time Limit Exceeded for Lead Updates/Inserts

Hello awesome devs! 

I have the followign trigger which works as intended, however when I do a mass upload or mass edit on more than 10 Lead records, I always get the "Apex CPU Time Limit Exceeded" error.  Can anyone tell me how to resolve this error in my code as if my users do a mass update of more than 10 lead records to assume ownership it throws this error and any other time an insert or update of more than 10 Lead records at a time. 

Thanks so much for any help you can provide,

Shawn

Trigger code:
 
trigger LeadCountOfTasks on Task (after delete, after insert, after undelete, after update) {
    Task [] tlist;
        if(Trigger.isDelete)
            tlist= Trigger.old;
        else
            tlist = trigger.new;
    set<id> lid = new set< id> ();
    
    If(!tlist.isEmpty()){
    for(Task ts : tlist)
    {   if(ts.WhoId!=null && ts.whatId == null)
    {
        If(string.valueOf(ts.WhoId).startsWith('00Q'))
        {
        lid.add(ts.Whoid);
    }
    }
    }
    If(lid.size()>0){
    Map <id,Task > tmap = new Map <id, Task>([select id, Whoid from Task where Whoid in:lid]);
    Map <id, Lead> lmap = new Map <id, Lead>([select id,Count_Activity__c from lead where id in:lid ]);
    
        If(lmap.size()>0){
       List<Lead> llist = [SELECT Id, Count_Activity__c FROM Lead WHERE ID IN:lmap.values()]; 
    for(lead l : lmap.values())
    {
        set<id> tids = new set <id>();
        for(Task tt : tmap.values())
        {
           if(tt.WhoId== l.Id)
            tids.add(tt.id);
        }
        if(l.Count_Activity__c!=tids.size())
        l.Count_Activity__c=tids.size();
        
              tlist = [select id, Whoid from task where whoid in:lid ];
        for(lead le :llist)
        {
            for(Task te:tlist)
            {
                if(tlist.size()>0)
                le.Count_Activity__c = tlist.size();
            }
        }
        
        
    }
    If(lmap.size()>0){
    update lmap.values();
    }
    }
    }
    }
}

 
v varaprasadv varaprasad
Hi Shawn.

I have modified your code but not tested.
 
trigger LeadCountOfTasks on Task (after delete, after insert, after undelete, after update) {
    Task [] tlist;
        if(Trigger.isDelete)
            tlist= Trigger.old;
        else
            tlist = trigger.new;
    set<id> lid = new set< id> ();
    
    If(!tlist.isEmpty()){
    for(Task ts : tlist)
    {   if(ts.WhoId!=null && ts.whatId == null)
    {
        If(string.valueOf(ts.WhoId).startsWith('00Q'))
        {
        lid.add(ts.Whoid);
    }
    }
    }
	}
    If(lid.size()>0){
	list<Lead> lstOfLeds = [select id,Count_Activity__c,(select id, Whoid from Tasks) from lead where id in:lid];
	list<Lead> lstOfupdateLeds = new list<Lead>();
	
 If(lstOfLeds.size()>0){      
    for(lead l : lstOfLeds){       
		      l.Count_Activity__c=l.tasks.size();
		     lstOfupdateLeds.add(l);       
    }
	update lstOfupdateLeds;
}

1) One Trigger Per Object
A single Apex Trigger is all you need for one particular object. If you develop multiple Triggers for a single object, you have no way of controlling the order of execution if those Triggers can run in the same contexts

2) Logic-less Triggers
If you write methods in your Triggers, those can’t be exposed for test purposes. You also can’t expose logic to be re-used anywhere else in your org.

3) Context-Specific Handler Methods
Create context-specific handler methods in Trigger handlers

4) Bulkify your Code
Bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a time.

5) Avoid SOQL Queries or DML statements inside FOR Loops
An individual Apex request gets a maximum of 100 SOQL queries before exceeding that governor limit. So if this trigger is invoked by a batch of more than 100 Account records, the governor limit will throw a runtime exception

6) Using Collections, Streamlining Queries, and Efficient For Loops
It is important to use Apex Collections to efficiently query data and store the data in memory. A combination of using collections and streamlining SOQL queries can substantially help writing efficient Apex code and avoid governor limits

7) Querying Large Data Sets
The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of queries causes you to exceed your heap limit, then a SOQL query for loop must be used instead. It can process multiple batches of records through the use of internal calls to query and queryMore

8) Use @future Appropriately
It is critical to write your Apex code to efficiently handle bulk or many records at a time. This is also true for asynchronous Apex methods (those annotated with the @future keyword). The differences between synchronous and asynchronous Apex can be found

9) Avoid Hardcoding IDs
When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange packages, it is essential to avoid hardcoding IDs in the Apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper data to operate against and not fail.

Few more Best Practices for Triggers
There should only be one trigger for each object.
Avoid complex logic in triggers. To simplify testing and resuse, triggers should delegate to Apex classes which contain the actual execution logic. See Mike Leach's excellent trigger template for more info.
Bulkify any "helper" classes and/or methods.
Trigers should be "bulkified" and be able to process up to 200 records for each call.
Execute DML statements using collections instead of individual records per DML statement.
Use Collections in SOQL "WHERE" clauses to retrieve all records back in single query
Use a consistent naming convention including the object name (e.g., AccountTrigger)

Hope this helps you.

Thanks
Varaprasad
v varaprasadv varaprasad
trigger LeadCountOfTasks on Task (after delete, after insert, after undelete, after update) {
    Task [] tlist;
        if(Trigger.isDelete)
            tlist= Trigger.old;
        else
            tlist = trigger.new;
    set<id> lid = new set< id> ();
    
    If(!tlist.isEmpty()){
    for(Task ts : tlist)
    {   if(ts.WhoId!=null && ts.whatId == null)
    {
        If(string.valueOf(ts.WhoId).startsWith('00Q'))
        {
        lid.add(ts.Whoid);
    }
    }
    }
	}
    If(lid.size()>0){
	list<Lead> lstOfLeds = [select id,Count_Activity__c,(select id, Whoid from Tasks) from lead where id in:lid];
	list<Lead> lstOfupdateLeds = new list<Lead>();
	
 If(lstOfLeds.size()>0){      
    for(lead l : lstOfLeds){       
		      l.Count_Activity__c=l.tasks.size();
		     lstOfupdateLeds.add(l);       
    }
	update lstOfupdateLeds;
}
}
}

 
David M. ReedDavid M. Reed
Is the purpose of this trigger to store a count of Tasks associated with each Lead on the Lead?

You have a lot of inefficiencies here. Most importantly, you have a SOQL query in a loop, which is a major factor leading to the error you're seeing. You need to bulkify this trigger by moving all SOQL and DML operations outside of your loops.

You're also doing a lot of unnecessary querying. I would structure this trigger something like this (in pseudo-code):
for each Task in the trigger:
   store the WhoId if the WhoId is of a Lead.

Perform a single SOQL query against the Task object using something like `SELECT count(Id), WhoId FROM Task WHERE WhoId IN :leadIds GROUP BY WhoId`.

Iterate through the AggregateResult objects returned by the query and update the Lead objects. You don't need to query the Leads - just create a new Lead object and populate only the Id and the Count_Activity__c field.

​Update the leads list.

 
Tuan LuTuan Lu
David is correct you should use an aggregate query to get the count. You dont need the actual record details. Also Tasks are one of the biggest tables in Salesforce so you should limit your use of that table.