0

Getting CPU time out error for below code:

Public class ResponseTimeCal
{
    Public boolean isFirst= True;
    Public DateTime BalVar;
    Public long BalHours;
    Public Long seconds,minutes,hours,milliseconds;
    Public void ResponseTimeCalMeth()
    {
        list<opportunity> l1 =[select Response_Date__c,createdDate,ownerID,Response_check__c  from opportunity where id in:Trigger.newMap.keySet()];
        for(opportunity oppObj:l1)
        {//opportunity oldOpp = System.Trigger.oldMap.get(oppObj.Id);
            If((oppObj.ownerID!='005n0000002KN6V')&&(oppObj.ownerID!=NULL)&&(oppObj.Response_check__c==False))
            {
                oppObj.Response_Date__c = system.now();
                oppObj.Response_check__c=True;
                system.debug('@@@Response date is' + oppObj.Response_Date__c );
                ResponseTimeCal(oppObj.createdDate,oppObj.Response_Date__c);          
            }
        }
    }

    Public void ResponseTimeCal(Datetime startDate, Datetime endDate)
    {
        system.debug('@@@method called');
        while(Date.valueOf(startDate)<=Date.valueOf(endDate))
        {
            if((isFirst==True)&&((startDate.format('EEE')!='Sat')||(startDate.format('EEE')!='Sun')))
            {
                milliseconds = startDate.getTime();
                BalVar = startDate;
                seconds = milliseconds / 1000;
                minutes = seconds / 60;
                hours = minutes / 60;
                BalHours = hours - 17;
                BalVar = BalVar.addDays(1);
                startDate=startDate.addDays(1);
                //valueof(oppObj.createdDate.format(‘MMMMM dd,yyyy hh:mm:ss a’));
                system.debug('Value of BalVar'+ BalHours);
                isFirst=false;
                //return(BalHours); 
            }
        }

    }
}
  • Welcome to SFSE, surinder! Please take a moment to visit the help center and scroll through the tour to familiarize yourself with the mechanics. When an answer solves the problem at hand, community etiquette is to accept it to indicate to the community you no longer need help with this problem. Of course you are under no obligation to do so. – Adrian Larson May 8 '17 at 20:48
5

You have a while loop that may never exit, because there are iterations where you do not increment startDate. If you never enter your if condition, you never increment startDate, and you will basically have while(true) with no break until you completely consume your CPU Limit. Move this line outside the conditional:

startDate = startDate.addDays(1);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.