0

When dataloading accounts - I keep getting an Apex CPU Timeout Error on the following action in the flow.

There aren't many contacts on the accounts being passed in - (less than 20?)

Am I missing something obvious?

public class AccountContactReassignment {

public class Request {
    @InvocableVariable(label='Account ID' required=true)
    public Id accountId;
}

@InvocableMethod(label='Reassign Contacts to the Account Owner' description='Reassign Accounts Child Contacts to Account Owner' category='Account')
public static void reassignRequests(List<Request> requests) {

    Set<Id> accountIds = new Set<Id>();
    List<Contact> contactsToUpdate = new List<Contact>();

    for(Request req: requests){
        accountIds.add(req.accountId);
    }        

    for(Contact c :  [select Id, AccountId, OwnerId, Account.OwnerId from Contact WHERE AccountID in: accountIds]){

        if(c.OwnerId != c.Account.OwnerId){
            c.OwnerId = c.Account.OwnerId;
            contactsToUpdate.add(c);
        }

    }

    if(contactsToUpdate.size() > 0){
        update contactsToUpdate;
    }

}

}

2
  • N.B. the line if(contactsToUpdate.size()>0) is superfluous, DML on empty lists does not burn any limits. Less-is-more
    – cropredy
    Aug 9, 2022 at 17:33
  • Thank you @cropredy
    – Josiah
    Aug 9, 2022 at 20:39

1 Answer 1

2

Governor limits are cumulative. That means that it doesn't matter which method uses too many resources, only that when those resources are exhausted, the code will stop running. As a simple example, imagine this code:

void doSomething() {
  method1();
  method2();
}
void method1() {
  for(Integer i = 0; i < 100; i++) {
    Contact c = [select id from contact limit 1];
  }
}
void method2() {
  Contact c = [select id from contact limit 1];
}

If you call doSomething, method2 will get an error saying "Too many SOQL: 101". However, in this rather obvious example, it is method1 that needs to be fixed.

Similarly, your invocable method is rather clearly not the problem. It may be because the flow is taking too long, or other triggers are involved that are using too much CPU time, etc.

The only way to know for sure is to use the Developer Console and check out the timings of the entire transaction.

2
  • Thanks. I'm going to try moving that particular invocable method into an asynchronous execution branch of the flow.
    – Josiah
    Aug 9, 2022 at 16:31
  • @Josiah That likely won't fix your problem. This code is fine, it's everything else that's using too much CPU time.
    – sfdcfox
    Aug 9, 2022 at 16:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .