+ Start a Discussion
gina.lasita1.3920678327807358E12gina.lasita1.3920678327807358E12 

Apex CPU Time Limit

Hello Salesforce community! I keep receiving the "Apex CPU Time Limit" error when adding many products to an opportunity after saving / adding more and then resaving.

I know that  my Apex execution time is too long, and that the Salesforce limit is exceeded. I read that the Maximum CPU time on the salesforce servers is 10,000 milliseconds (Synchronous limit) 60,000 milliseconds (Asynchronous limit). The answer to fix this issue is to refine my code by removing unnecessary loop for better efficiency. (Ex: Inserting a "Map" field to bypass some things)... etc. Can anyone assist me when time permits? Please see my "opportunityProductEntry" visualforce page code below:

<apex:page standardController="Opportunity" extensions="opportunityProductEntryExtension" action="{!priceBookCheck}" >
<apex:sectionHeader Title="Manage {!$ObjectType.Product2.LabelPlural}" subtitle="{!opportunity.Name}"/>
<apex:messages style="color:red"/>
<style type="text/css">
.search{
font-size:14pt;
margin-right: 20px;}
.fyi{
color:red;
font-style:italic;}
.label{
margin-right:10px;
font-weight:bold;
}
        .custPopup{
           background-color: white;
            border-width: 2px;
            border-style: solid;
            z-index: 9999;
            left: 50%;
            padding:10px;
            position: absolute;
            /* These are the 3 css properties you will need to change so the popup
            displays in the center of the screen. First set the width. Then set
            margin-left to negative half of what the width is. You can add
            the height property for a fixed size pop up if you want.*/
            width: 500px;
            margin-left: -250px;
            top:100px;
        }
        .popupBackground{
            background-color:green;
            opacity: 0.20;
            filter: alpha(opacity = 20);
            position: absolute;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            z-index: 9998;
        }
</style>
<script type='text/javascript'>
var waitTime = 1;
var countDown = waitTime+1;
var started = false;   
function resetTimer(){
countDown=waitTime+1;
if(started==false){
started=true;
                runCountDown();
            }
        }
function runCountDown(){
countDown--;
if(countDown<=0){
fetchResults();
started=false;
            }
else{
window.setTimeout(runCountDown,1000);
            }
        }
function checkBoxChecked(isChecked, obj)
        {
            if(isChecked.checked)
            {         
                recs +=  obj + ',';
                ShowPopup(obj);
            }
        }
      
        function selRelatedRecs(isChecked, obj)
        {
            if(isChecked.checked)
                recs += obj + ',';
            else
            {
                var str = obj + ',';
                recs = recs.replace(str, ''); 
            }
        }
      
        function addRecs()
        {
            addSelectedRecs(recs);
            return false;
        }
    </script>

    <apex:form >
  
        <apex:outputPanel id="mainBody">
      
            <apex:outputLabel styleClass="label">PriceBook: </apex:outputLabel>
            <apex:outputText value="{!theBook.Name}"/>&nbsp;
            <apex:commandLink action="{!changePricebook}" value="change" immediate="true"/>
            <br/>
            <!-- not everyone is using multi-currency, so this section may or may not show -->
            <apex:outputPanel rendered="{!multipleCurrencies}">
                <apex:outputLabel styleClass="label">Currency: </apex:outputLabel>
                <apex:outputText value="{!chosenCurrency}"/>
                <br/>
            </apex:outputPanel>
            <br/>
          
<!-- this is the upper table... a.k.a. the "Shopping Cart"-->

            <!-- notice we use a lot of $ObjectType merge fields... I did that because if you have changed the labels of fields or objects it will reflect your own lingo -->
            <apex:pageBlock title="Selected {!$ObjectType.Product2.LabelPlural}" id="selected" >
                <apex:pageMessages id="pgMsg" />       
                <apex:pageblockTable value="{!shoppingCart}" var="s">
                    <apex:column >
                        <apex:commandLink value="Remove" action="{!removeFromShoppingCart}" reRender="selected,searchResults" immediate="true">
                            <!-- this param is how we send an argument to the controller, so it knows which row we clicked 'remove' on -->
                            <apex:param value="{!s.PriceBookEntryId}" assignTo="{!toUnselect}" name="toUnselect"/>
                        </apex:commandLink>
                    </apex:column>
                  
                    <apex:column headerValue="{!$ObjectType.Product2.LabelPlural}" value="{!s.PriceBookEntry.Product2.Name}"/>
                    <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.Quantity.Label}">
                        <apex:inputField value="{!s.Quantity}" style="width:70px" required="true" onkeyup="refreshTotals();"/>
                    </apex:column>
                  
                    <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.Hours_Needed__c.Label}">
                        <apex:inputField value="{!s.Hours_Needed__c}" style="width:70px" required="false" onkeyup="refreshTotals();"/>
                    </apex:column>
                  
                    <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.Feet_Needed__c.Label}">
                        <apex:inputField value="{!s.Feet_Needed__c}" style="width:70px" required="false" onkeyup="refreshTotals();"/>
                    </apex:column>
                  
                    <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.ListPrice.Label}">
                        <apex:inputField value="{!s.ListPrice}" style="width:70px" required="false" onkeyup="refreshTotals();"/>
                    </apex:column>
                  
                    <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.UnitPrice.Label}">
                        <apex:inputField value="{!s.UnitPrice}" style="width:70px" required="true" onkeyup="refreshTotals();"/>
                    </apex:column>
                  
                    <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.Description.Label}">
                        <apex:inputField value="{!s.Description}" required="false"/>
                    </apex:column>
                  
                </apex:pageblockTable>
                <apex:pageBlockButtons >
                    <apex:commandButton action="{!onSave}" value="Save"/>
                    <apex:commandButton action="{!onCancel}" value="Cancel" immediate="true"/>
                </apex:pageBlockButtons>
          
            </apex:pageBlock>
  
<!-- this is the lower table: search bar and search results -->
  
            <apex:pageBlock id="pb">
          
                <apex:outputPanel styleClass="search">
                    Search for {!$ObjectType.Product2.LabelPlural}:
                </apex:outputPanel>

                <apex:actionRegion renderRegionOnly="false" immediate="true">
               
                    <apex:actionFunction name="fetchResults" action="{!updateAvailableList}"  reRender="searchResults" status="searchStatus"/>
                  
                    <!-- here we invoke the scripting to get out fancy 'no button' search bar to work -->
                    <apex:inputText value="{!searchString}" onkeydown="if(event.keyCode==13){this.blur();}else{resetTimer();}" style="width:300px"/>
                    &nbsp;&nbsp;
                    <i>
                        <!-- actionStatus component makes it easy to let the user know when a search is underway -->
                        <apex:actionStatus id="searchStatus" startText="searching..." stopText=" "/>
                    </i>
                  
                </apex:actionRegion>
          
                <br/>
                <br/>
            
                <apex:pageBlockButtons >
                        <apex:commandButton onclick="return addRecs();" value="Add Selected Records" />
                        <apex:commandButton action="{!reset}" value="Reset Selection" immediate="true" />
                </apex:pageBlockButtons>  
                <apex:actionFunction name="addSelectedRecs" action="{!addSelectedRecords}"  immediate="true" rerender="selected">
                    <apex:param value="" assignTo="{!selectedRelatedProds}" name="selectedRelatedProds"/>
</apex:actionFunction>
<apex:outputPanel id="searchResults">
<apex:pageBlockTable value="{!AvailableProducts}" var="a">
<apex:column >
<apex:inputCheckbox id="idSelected" onclick="checkBoxChecked(this,'{!a.Id}');"/>
</apex:column>
<apex:column headerValue="{!$ObjectType.Product2.Fields.Name.Label}">
<apex:commandLink action="/{!a.Product2.Id}" value="{!a.Product2.Name}"/>
</apex:column>
<apex:column headerValue="{!$ObjectType.PricebookEntry.Fields.UnitPrice.Label}" value="{!a.UnitPrice}"/>
<!--
<apex:column headerValue="{!$ObjectType.Product2.Fields.Description.Label}" value="{!a.Product2.Description}"/>
-->
<apex:column headerValue="{!$ObjectType.Product2.Fields.Family.Label}" value="{!a.Product2.Family}"/>
<br/>
<div>
<apex:panelGroup >
<apex:commandLink action="{!First}" value="First"  immediate="true" reRender="pb" />           
&nbsp;&nbsp;
<apex:commandLink action="{!Previous}" reRender="pb" value="Previous"  immediate="true" rendered="{!hasPrevious}"/>           
&nbsp;&nbsp;
<apex:outputLabel > Page No#&nbsp;{!pageno} </apex:outputLabel>&nbsp;&nbsp;&nbsp;&nbsp;
<apex:commandLink action="{!Next}" value="Next"  immediate="true" rendered="{!hasNext}" reRender="pb"/>           
&nbsp;&nbsp;
<apex:commandLink action="{!Last}" value="Last"  immediate="true" reRender="pb"/>           
&nbsp;&nbsp;
</apex:panelGroup>
</div>
</apex:outputPanel>
<apex:outputPanel id="custompopup">
<apex:outputPanel styleClass="popupBackground" layout="block" rendered="{!displayPopUp}"/>
<apex:outputPanel styleClass="custPopup" layout="block" rendered="{!displayPopUp}">
<apex:pageBlock title="Related Products">
<apex:pageBlockTable value="{!RelatedProducts}" var="a">
<apex:column >
<apex:inputCheckbox id="idRelSelected" onclick="selRelatedRecs(this, '{!a.Id}');"/>
</apex:column>
<apex:column headerValue="{!$ObjectType.Product2.Fields.Name.Label}">
<apex:commandLink action="/{!a.Product2.Id}" value="{!a.Product2.Name}"/>
</apex:column>
<apex:column headerValue="{!$ObjectType.PricebookEntry.Fields.UnitPrice.Label}" value="{!a.UnitPrice}"/>
<!--
<apex:column headerValue="{!$ObjectType.Product2.Fields.Description.Label}" value="{!a.Product2.Description}"/>
-->
<apex:column headerValue="{!$ObjectType.Product2.Fields.Family.Label}" value="{!a.Product2.Family}"/>
</apex:pageBlockTable><br/>
<apex:pageBlockButtons >
<apex:commandButton value="Close" action="{!closePopup}"  immediate="true" rerender="custompopup" />
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:outputPanel>
</apex:outputPanel>
<apex:actionFunction name="ShowPopup" action="{!showPopup}"  immediate="true" rerender="custompopup">
<apex:param value="" assignTo="{!toSelect}" name="toSelect"/>
</apex:actionFunction>
</apex:pageBlock>
 </apex:outputPanel>
</apex:form>
</apex:page>

Thank you!

Andrew
George thomasGeorge thomas
Hi Andrew,


Could you please post the extension-opportunityProductEntryExtension for the above visulaforce page.


Thanks,
George
Mahesh GaikwadMahesh Gaikwad
Hi,

Please debug your javascript function  runCountDown, because you set timeout of one second it may be called again and again and after 10 such calls you get timeout exeception

Thanks,
Mahesh
gina.lasita1.3920678327807358E12gina.lasita1.3920678327807358E12

George and/or Mahesh,

Would either of you be able to help and do a screen share with me? I am still learning Salesforce.

When time permits, please let me know.

Thank you,

Andrew