Contact Mass Update – Apex CPU Time Limit Exceeded?

Question
I am trying to perform a mass update on Contact records using Execute Anonymous, but I keep getting the following error:
System.LimitException: Apex CPU Time Limit Exceeded
Here is the code I am using:
List<Contact> contactList = [SELECT Id, Mass_Update_Checkbox__c FROM Contact LIMIT 1000];
for (Contact contact : contactList) {
contact.Mass_Update_Checkbox__c = TRUE;
}
update contactList;
What is causing this error, and how can I optimize my approach to avoid hitting the CPU time limit?
Answer
The error occurs because iterating over a large number of records in a loop and updating them directly in-memory can cause excessive CPU time consumption. Instead of a loop, consider using a more efficient approach like batch processing.
Master Salesforce with expert-led salesforce online training at CRS Info Solutions—join our demo session now!!!
One solution is to use a Batch Apex class to handle the update in chunks, reducing CPU time per transaction.
Batch Apex Approach
public class ContactMassUpdateBatch implements Database.Batchable<sObject> {
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator('SELECT Id FROM Contact WHERE Mass_Update_Checkbox__c = FALSE');
}
public void execute(Database.BatchableContext bc, List<Contact> scope) {
for (Contact c : scope) {
c.Mass_Update_Checkbox__c = TRUE;
}
update scope;
}
public void finish(Database.BatchableContext bc) {}
}
To execute the batch, run the following in Execute Anonymous:
Database.executeBatch(new ContactMassUpdateBatch(), 200);
Swiss Army Knife Batch Processing Approach
An alternative is a more flexible batch processing utility that allows executing mass updates dynamically using an anonymous execution batch pattern.
Database.executeBatch(
new ExecAnonBatch(
Generators.fromQuery('SELECT Id FROM Contact'),
Executors.updateField(Contact.Mass_Update_Checkbox__c, true))
);
This approach is part of a broader utility that enables bulk updates, record creation, deletion, undeleting, and more. Here is an example implementation:
public class ExecAnonBatch implements Database.Batchable<Object> {
public interface generator {
Object generate();
}
public interface executor {
void execute(Object[] values);
}
generator gen;
executor exec;
public ExecAnonBatch(generator theGenerator, executor theExecutor) {
gen = theGenerator;
exec = theExecutor;
}
public Iterable<Object> start(Database.BatchableContext context) {
return (Iterable<Object>) gen.generate();
}
public void execute(Database.BatchableContext context, Object[] scope) {
exec.execute(scope);
}
public void finish(Database.BatchableContext context) {}
}
public class Generators {
class QueryGenerator implements ExecAnonBatch.generator {
String queryString;
QueryGenerator(String query) {
queryString = query;
}
public Object generate() {
return Database.getQueryLocator(queryString);
}
}
public static ExecAnonBatch.generator fromQuery(String query) {
return new QueryGenerator(query);
}
}
public class Executors {
class FieldUpdate implements ExecAnonBatch.executor {
SObjectField field;
Object value;
FieldUpdate(SObjectField updateField, Object fieldValue) {
field = updateField;
value = fieldValue;
}
public void execute(Object[] scope) {
SObject[] records = (SObject[])scope;
for(SObject record: records) {
record.put(field, value);
}
Database.update(records, false);
}
}
public static ExecAnonBatch.executor updateField(SObjectField field, Object value) {
return new FieldUpdate(field, value);
}
}
Unit Test for the Swiss Army Knife Batch
@isTest
class ExecAnonBatchTest {
@isTest
static void test() {
Test.startTest();
Database.executeBatch(
new ExecAnonBatch(
Generators.fromQuery('SELECT Id FROM User LIMIT 1'),
Executors.updateField(User.LastName, 'Doe')));
Test.stopTest();
System.assertEquals('Doe', [SELECT LastName FROM User ORDER BY LastModifiedDate DESC LIMIT 1].LastName);
}
}
Accelerate Your Career with Salesforce Training in Mumbai
Are you ready to elevate your career in Mumbai’s thriving Salesforce ecosystem? At CRS Info Solutions, we offer Salesforce online training that equips you with the skills to stand out. Our comprehensive program, led by experienced industry professionals, covers essential areas like Salesforce Administration, Development, and cutting-edge AI modules. With a focus on hands-on learning and real-time projects, you’ll gain practical expertise to tackle real-world challenges confidently.
Whether you’re embarking on your Salesforce journey or aiming to enhance your skill set, our tailored training programs are designed to meet your unique needs. Salesforce training in Mumbai From mastering certification requirements to acing job interviews, we provide personalized guidance, in-depth course materials, and expert strategies for success.
Join our free demo session today and take the first step toward a prosperous Salesforce career in Mumbai!!!