System.LimitException: Apex CPU time limit exceeded Stack Trace: (System Code) Class.OpportunityTriggerHandler.OnAfterInsert: line 63, column 1 Trigger.OpportunityTriggers: line 30, column 1

What is reason for this kind of Errors after Winter 15 release??

public void OnAfterInsert(Map<Id, Opportunity> newOppMap, Map<Id, Opportunity> oldOppMap) {
    if (Limits.getQueries() > 50 && Test.isRunningTest()) //Escaping from the old test classes issues
    prodMap = new Map<String, Product2>();
    for (Product2 p : [SELECT id, ProductCode, UniqueSageCode__c
                       FROM Product2]) {
        system.debug('------------QueryProductsCheck------------' + p);
        prodMap.put(p.UniqueSageCode__c, p);


    List<PriceBookEntry> listPBE;
    producsPBEMap = new Map<id, List<PriceBookEntry>>();
    for (PriceBookEntry pbe : [SELECT id, Product2Id, ProductCode, PriceBook2Id, UnitPrice
                               FROM PriceBookEntry]) {
        system.debug('---------QueryPriceBookEntryCheck--------------' + pbe);
        if (producsPBEMap.containskey(pbe.Product2Id)) {
        } else {
            listPBE = new List<PriceBookEntry> {pbe};
            producsPBEMap.put(pbe.Product2Id, listPBE);
  • It would be extremely difficult to answer this without looking at the code. Its most likely some part of your code is doing stuff which is taking up a lot of time to complete. There was a similar problem reported earlier as well salesforce.stackexchange.com/questions/47035/…. Are you having problems after winter 15 release only?
    – Prady
    Nov 5 '14 at 7:05
  • What are you trying to do with this trigger. A simple explanation of business rule could help. I can see you are populating all the products and pricebookentey's into maps. IF the products and pricebookentry records are at a higher count then we could run into this limit exceptions. Try limiting them with a where condition.
    – Prady
    Nov 5 '14 at 7:37
  • 1
    also if this only occurs in a test class, you could use Test.StartTest() and Test.StopTest() to reset the governor limits between preparing your data and calling the actual function that you want to test. Nov 5 '14 at 10:16
  • The code that is mentioned in the error may/may not be the cause of the issue. The error means that you have used up too much of the CPU time on the server and SF are killing the process. The issue could be in any code that executed before the code you have posted. Have a look a the logs to see if you can see any repeating code. Code like Limits.getQueries() > 50 suggests you may have had problems like this in the past
    – BarCotter
    Nov 5 '14 at 10:33

Your Answer

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

Browse other questions tagged or ask your own question.