Question
I’m attempting to perform a mass update on Contacts using Execute Anonymous, but I keep encountering the following error:
System.LimitException: Apex CPU Time Limit Exceeded
Here’s the code I’m 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;Why is this happening, and how can I optimize my approach to avoid hitting the CPU time limit?
Answer
The Apex CPU time limit error occurs when the total processing time for a transaction exceeds 10 seconds, which is a hard limit in Salesforce. This is different from SOQL, DML, or heap size limits, as it measures the actual execution time of the Apex code itself.
Even though your query is limited to 1000 records, the error can still occur due to:
Background automation such as triggers, workflow rules, and Process Builder flows that execute on Contact updates.
Inefficient Apex processing, especially if the org is handling multiple processes at the same time.
Large transaction scope, where all records are updated in a single transaction rather than breaking them into smaller chunks.
Optimized Solution Using Batch Apex
A better approach is to use Batch Apex, which processes records in smaller batches instead of all at once. This reduces CPU time per transaction and helps avoid hitting the limit.
Here’s a Batch Apex class that updates the Mass_Update_Checkbox__c field efficiently:
public class ContactMassUpdateBatch implements Database.Batchable<SObject> {
public Database.QueryLocator start(Database.BatchableContext context) {
return Database.getQueryLocator('SELECT Id FROM Contact WHERE Mass_Update_Checkbox__c = FALSE');
}
public void execute(Database.BatchableContext context, List<SObject> scope) {
for (SObject record : scope) {
Contact contact = (Contact) record;
contact.Mass_Update_Checkbox__c = TRUE;
}
update scope;
}
public void finish(Database.BatchableContext context) {
System.debug('Batch update completed.');
}
}Explanation of the Code
The ContactMassUpdateBatch class is a Batch Apex implementation designed to efficiently update the Mass_Update_Checkbox__c field on Contact records.
startMethod:
Queries all Contact records whereMass_Update_Checkbox__c = FALSE.
UsesDatabase.getQueryLocatorto return the records in manageable chunks.executeMethod:
Runs for each batch of records (default batch size is 200).
Iterates through the retrieved contacts and setsMass_Update_Checkbox__c = TRUE.finishMethod:
Executes after all batches are processed.
Logs a message confirming batch completion.
Why This Works?
Processes records in small batches (default 200 at a time) instead of a single large transaction.
Each batch runs as a separate transaction, preventing CPU time limits from being exceeded.
More scalable, allowing you to update thousands or millions of records without hitting governor limits.
To prevent “Apex CPU Time Limit Exceeded” errors when mass updating records:
Use Batch Apex instead of Execute Anonymous, as it breaks the update into smaller, manageable transactions.
Reduce automation overhead, ensuring that triggers and workflows are optimized.
Consider a reusable batch framework if you frequently need to update records across different objects.
Enroll for Salesforce Training Designed for Career Building Success
Our Salesforce course is thoughtfully designed to provide a comprehensive understanding of the Salesforce platform, equipping you with the essential skills to succeed in the CRM industry. The program covers vital modules like Salesforce Admin, Developer, and AI, combining theoretical learning with hands-on application. By engaging in real-world projects and interactive exercises, you’ll gain the expertise to solve complex business challenges using Salesforce solutions. Our seasoned instructors ensure you develop both technical proficiency and industry knowledge to thrive in the Salesforce ecosystem.
Beyond technical expertise, our Salesforce training in Hyderabad includes personalized mentorship, certification support, and interview preparation to boost your career prospects. You’ll gain access to in-depth study resources, real-time project experience, and continuous guidance throughout your learning journey. By the end of the course, you’ll be well-prepared for certification exams and possess the problem-solving skills employers seek. Take the first step toward a rewarding Salesforce career—enroll in a Free Demo today!


Leave a Reply
You must be logged in to post a comment.