0

I have the following apex file to update about 600 opportunity records that have status1 as Active and status2 as Inactive. status2 is a formula, status1 is a text field.

Running this via Execute Anonymous gives this error:

system.LimitException: Apex CPU time limit exceeded

public void updateStatus() {
        List<Opportunity> records = [
          SELECT Id FROM Opportunity WHERE status1__c = 'Active'
          AND status2__c = 'Inactive'
        ];

        for (Opportunity record : records)
        {
           record.status1__c = 'Inactive';
        }
        update records;   

    }

I played with it, the query part runs ok and shows the 600 rows selected in the logs. I think the update part is giving the timeout error. Not sure why. 600 rows shouldn't be too many. Or is it too many rows to update?

2
  • 2
    is there triggers / workflow / process builder in Opportunity object? Also, it is not a time out, but you exceeded the CPU time limit. It is different...
    – m Peixoto
    Mar 28, 2019 at 14:36
  • yes, there is process builder
    – apadana
    Mar 28, 2019 at 14:37

1 Answer 1

2

This error occurs because there's too much logic going on. You either have too many Process Builders, flows, triggers, or some combination thereof that's causing this problem. The only two solutions are to limit the number of records you update, or optimize your org to use less CPU time.

In theory, Salesforce allows updating 10,000 records at once in an execute anonymous script, but if you have a lot of custom business logic, that number can be reduced drastically. In one particular org I worked in, we could only update about 10 records at a time without hitting this error.

Since it looks like you're going for a one-off update, simply limit it to a smaller value and run the script until you have no more records to process (3x). Add a LIMIT 200 to your query, and your updates should finish correctly.

1
  • Worked like a charm. Thanks!
    – apadana
    Mar 28, 2019 at 14:50

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