How to optimize this code ,I am continuously getting "Apex CPU Limit Error" Can anyone help me out with optimize solution Here is the code :- Batch Size :50 passing here are some number of records we have opportunities: 1 million records. opportunity history: 1 million records.
global class LastStateUpdatedBatch implements Database.Batchable<sObject> {
String query;
global LastStateUpdatedBatch() {
query = 'Select Last_Stage_Update__c, (Select CreatedDate, StageName From OpportunityHistories order by CreatedDate desc) From Opportunity where Last_Stage_Update__c = null AND IsClosed = false ';
}
global Database.QueryLocator start(Database.BatchableContext BC) {
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<sObject> scope) {
List<Opportunity> listOfOldOpp = (List<Opportunity>)scope;
for( Opportunity opp : listOfOldOpp){
String lastOppStage = opp.OpportunityHistories[0].StageName;
DateTime lastUpdate = opp.OpportunityHistories[opp.OpportunityHistories.size()-1].CreatedDate;
DateTime previousStageChangeDate = opp.OpportunityHistories[0].CreatedDate;
List<OpportunityHistory> ListOfOpportunityHistories = opp.OpportunityHistories;
for(OpportunityHistory opphis :ListOfOpportunityHistories){
if(lastOppStage != opphis.StageName && opp.Last_Stage_Update__c == null){
lastUpdate = previousStageChangeDate;
break;
}
previousStageChangeDate = opphis.CreatedDate;
}
opp.Last_Stage_Update__c = lastUpdate.Date();
}
update listOfOldOpp;
}
global void finish(Database.BatchableContext BC) {
}
}