function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SriniSrini 

While we are trying to run the batch apex we are facing "Apex CPU time limit "

Hi Team,

While we are trying to run the batch apex we are facing the" First error: Apex CPU time limit exceeded" .why this error is  occured and  how to resolve this please can anyone help me..

Thanks in advance..
Best Answer chosen by Srini
N.M. SharmaN.M. Sharma
Hi,
In your code first you make a for loop for scope and the you fetch account and using Account list you make 2 for look Thats why its thowing CPU time limit error.

So i think if you going to change your code its sounds meassy. 
Have you reduce your batch Size?
Thanks
If my answers is giving you help please mark it as solution thanks  :)
 

All Answers

N.M. SharmaN.M. Sharma
It seems like you update somthing into the batch and the updated object have trigger also.
You need to reduce the batch size and then i will working fine
ID batchprocessid = Database.executeBatch(BatchClassName, BatchSize);
you can put batch size. Actually the default batch size is 200 and i think for 200 recods the code flow is too long.

Try this
ID batchprocessid = Database.executeBatch(ABCD, 50);
SriniSrini
@Sharma :  In anonymous block we have written like  this

MasterAccountNewLogoDate  btchnew = new MasterAccountNewLogoDate ();
database.executeBatch(btchnew,200);

can you please tell me how we can use ID batchproceesid's.

Thanks
N.M. SharmaN.M. Sharma
Hi Srini

Every Batch returns its Job id. Like if a batch is in running process using batch id we can check our batch status and other things.

For Example:
ID batchprocessid = Database.executeBatch(ABCD, 50);
AsyncApexJob  aApexJobObj = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,TotalJobItems, CreatedBy.Email FROM AsyncApexJob WHERE Id = : batchprocessid ];
system.debug('Batch Details: ' + aApexJobObj );

It will provide you Batch details according to its id.

Thanks
SriniSrini
Hi @Sharma : Please check which we are trying as of now please let me know where we are made the mistakes since last 4 days we are facing same issue...Please it's very needed.

global class MasterAccountNewLogoDate implements Database.Batchable<AggregateResult>{

        /// get all Account Group by Ultimate_Parent_ID__c
        
        /* START Method */
        
        global Iterable<AggregateResult> start(database.batchablecontext BC){
              return (AccountsWithParentID ); 
        }
        
        List<AggregateResult> AccountsWithParentID = [Select Ultimate_Parent_ID__c, Min(SW_New_Landing_Date_Formula__c) NewLogo_StatusDate from Account where Ultimate_Parent_ID__c!=Null and SW_New_Landing_Date_Formula__c!=Null group by Ultimate_Parent_ID__c];

        
        /* EXECUTE Method */
        global void execute(Database.BatchableContext BC, List<AggregateResult> scope){        
            
                Map<id, String> AccountNewLogoStatus = new Map<id, String>();
                Map<id, date> AccountNewlogodate = new Map<id, date>();
                List<account> AccountToUpdate = new List<Account>();
                List<id> AccountId = new List<id>();
                String tempStatus='';
                
                ////loop through the Ultimate Parent Ids and create map of id and newlogo dates
                for (AggregateResult ParentIds : scope){
                        AccountId.add((ID)ParentIds.get('Ultimate_Parent_ID__c'));
                        AccountNewlogodate.put((ID)ParentIds.get('Ultimate_Parent_ID__c'),(Date)ParentIds.get('NewLogo_StatusDate')); 
                        }
               Account[] AllAccounts = [SELECT id,SW_Status_Formula__c,Ultimate_Parent_ID__c,GED_Master_Account_Status__c,GED_Master_Account_New_Logo_Date__c from Account where Ultimate_Parent_ID__c in :AccountId ];
                  
                                
                //create map of the different statuses 
                for(Account Acc: AllAccounts ){ 
                    if(AccountNewLogoStatus.get(Acc.Ultimate_Parent_ID__c)!=Null){                       
                        tempStatus = AccountNewLogoStatus.get(Acc.Ultimate_Parent_ID__c);
                        
                        if(Acc.SW_Status_Formula__c =='Prospect' ){
                            tempStatus = tempStatus + ',P';                        
                        }
                        if(Acc.SW_Status_Formula__c =='Customer (New Landing)' ){
                            tempStatus = tempStatus + ',N';
                        }
                        if(Acc.SW_Status_Formula__c =='Customer (Active)' ){
                            tempStatus = tempStatus + ',A';
                        }
                        if(Acc.SW_Status_Formula__c =='Customer (Dormant)' ){
                            tempStatus = tempStatus + ',D';
                        }
                        AccountNewLogoStatus.put(Acc.Ultimate_Parent_ID__c,tempStatus);
                        tempStatus ='';
                    }
                    else
                    {
                        if(Acc.SW_Status_Formula__c =='Prospect' ){
                            AccountNewLogoStatus.put(Acc.Ultimate_Parent_ID__c,'P');
                        }
                        if(Acc.SW_Status_Formula__c =='Customer (New Landing)'){
                            AccountNewLogoStatus.put(Acc.Ultimate_Parent_ID__c,'N');
                        }
                        if(Acc.SW_Status_Formula__c =='Customer (Active)'){
                            AccountNewLogoStatus.put(Acc.Ultimate_Parent_ID__c,'A');
                        }
                        if(Acc.SW_Status_Formula__c =='Customer (Dormant)'){
                            AccountNewLogoStatus.put(Acc.Ultimate_Parent_ID__c,'D');
                        }
                    }
                }
                
                //loop through to update the NL_status
                for (Account Acc: AllAccounts ){   
                    Acc.GED_Master_Account_New_Logo_Date__c =AccountNewlogodate.get(Acc.Ultimate_Parent_ID__c);
                     //Acc.GED_Master_Account_Status__c =AccountNewlogodate.ValueOf(Acc.Ultimate_Parent_ID__c);
                    if (AccountNewLogoStatus.get(Acc.Ultimate_Parent_ID__c)!=Null){
                        tempStatus=AccountNewLogoStatus.get(Acc.Ultimate_Parent_ID__c);
                        if(tempStatus.contains('N') && tempStatus.containsNone('A') && tempStatus.containsNone('D')){
                            Acc.GED_Master_Account_Status__c ='Customer (New Landing)';
                        }
                        if(tempStatus.contains('D') && tempStatus.containsNone('A') && tempStatus.containsNone('N')){
                            Acc.GED_Master_Account_Status__c ='Customer (Dormant)';
                        }
                        if(tempStatus.contains('P') && tempStatus.containsNone('A') && tempStatus.containsNone('D')){
                            Acc.GED_Master_Account_Status__c ='Prospect';
                        }
                        if(tempStatus.contains('A')){
                            Acc.GED_Master_Account_Status__c ='Customer (Active)';
                        }           
                    }
                    AccountToUpdate.add(Acc); 
                } 
            if(AccountToUpdate.size()>0){
                Update AccountToUpdate;
            }         
                  
            }//execute loop
            
        /* FINISH Method */
        global void finish(Database.BatchableContext info){
               
        }//global void finish loop
}//global class loop

Thanks
N.M. SharmaN.M. Sharma
Hi,
In your code first you make a for loop for scope and the you fetch account and using Account list you make 2 for look Thats why its thowing CPU time limit error.

So i think if you going to change your code its sounds meassy. 
Have you reduce your batch Size?
Thanks
If my answers is giving you help please mark it as solution thanks  :)
 
This was selected as the best answer
SriniSrini
Hi Sharma,

Thanks for your suggestions. Can you please help me on that based on the  above code it will help us .

Thanks
N.M. SharmaN.M. Sharma
Hi Srini,

At the current position Reduce the BatchSize is the best Solution for removing CPU time limit error. Call the batch with only 10 records.
And If you facing any other error please let me know.

Thanks
SriniSrini
Hi Sharma,

We have tried Reducing the BatchSize,still facing same error.it has taking long time. don't know how we can acheving this error.please help me.

Thanks
N.M. SharmaN.M. Sharma
Can you provide me your Login passward on nitin0510sh@gmail.com
SriniSrini
don't mine it's not possible to provide credentials it's singlesign enabled.can you please provide your contact details so that i will call you.
 
N.M. SharmaN.M. Sharma
What's your email id i will share my contact on it or send me a mail on my email address.
SriniSrini
please check your mail box
SriniSrini
Hi Sharma,

Can you please help me on the writting test calss for the above class

Thanks
 
N.M. SharmaN.M. Sharma
Hi Srini,
ya Sure
First of all take a visit on this link: https://developer.salesforce.com/docs/atlas.en-us.apex_workbook.meta/apex_workbook/apex_batch_2.htm
 
@isTest
private class MasterAccountNewLogoDateTest{

    static testmethod void testMethod() {
        // Insert your Account here with Ultimate_Parent_ID__c and SW_New_Landing_Date_Formula__c.
       

       Test.startTest();
       MasterAccountNewLogoDate batchObj = new MasterAccountNewLogoDate();
       Database.executeBatch(batchObj);
       Test.stopTest();
    }
}
Thanks