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
FazurFazur 

Apex CPU time limit exceed exception

Hi Team,

I am getting salesforce "Apex CPU time limit exceed exception" in the below code. Please help me to optimize the code or how to sort out this issue. Any help would be greatly appriciated. 


public static Map<String, Object> getCFAccountOverdue(Set<String> cfAccountIdSet ) {
    Map<String, Object> cfAccountOverdueMap = new Map<String, Object>();
    Map<String, Decimal> overdueDateRangeMap = new Map<String, Decimal>();
    
    for(Schema.pickListEntry eachVal : CF_Claim__c.Overdue_Date_Ranges__c.getDescribe().getPicklistValues()){
        overdueDateRangeMap.put(eachVal.getValue(), 0);
    }
        for(CF_Claim__c eachClaim : [SELECT CF_Account__c, Overdue_In_Days__c, Amount__c  FROM CF_Claim__c  WHERE CF_Account__c IN:cfAccountIdSet AND Status__c = 'Open' ORDER BY CF_Account__c,Overdue_In_Days__c Nulls last]) {                
            if( !cfAccountOverdueMap.containsKey(eachClaim.CF_Account__c) ) {   
                Map<String, Decimal> dateRangeMap = new Map<String, Decimal>(); 
                dateRangeMap.putAll(overdueDateRangeMap);
                dateRangeMap.put(eachClaim.Overdue_In_Days__c, eachClaim.Amount__c != null ? eachClaim.Amount__c : 0);
                cfAccountOverdueMap.put(eachClaim.CF_Account__c, dateRangeMap);                    
            }else {
                Map<String, Decimal> dateRangeMap = (Map<String, Decimal>)cfAccountOverdueMap.get(eachClaim.CF_Account__c);
                dateRangeMap.put(eachClaim.Overdue_In_Days__c, ((dateRangeMap.get(eachClaim.Overdue_In_Days__c)) + (eachClaim.Amount__c != null ? eachClaim.Amount__c : 0)));
                cfAccountOverdueMap.put(eachClaim.CF_Account__c, dateRangeMap);
            }
        }
    return cfAccountOverdueMap; 
}
bretondevbretondev
Your code looks good.
Do you really need it to be synchronous?
If not , have you thought about Queauble Apex or Batch Apex ?

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_queueing_jobs.htm
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch.htm
FazurFazur
Hi Bretondev,

Thanks for your reply. But i am not using this code in trigger or batch class .... i am displaying more than 50k records in visualforce page using JS remoting.
bretondevbretondev
I am sorry but if you want to display all the records at once in your page, I cannot help you.
If I was in your situation, I would use pagination
Ravi Dutt SharmaRavi Dutt Sharma
Displaying 50k records at once? Will that be useful to the business? I dont think so. Iterating over 50k records in Apex will always result in a time limit issue. You should either limit the records or implement pagination to solve this.