When we are running the batchApex we are facing "CPU time limit exceeded". Please find my below Batch Apex which we are tried and let me know where we made the mistakes in current Logic.
Batch:
global class OpportunityDays implements Database.Batchable {
Public List<Opportunity> lstOpp;
global Database.QueryLocator start(Database.BatchableContext BC){
String query = 'Select id, Name, StageName, Software_Product_Count__c, CW_in_Last_30_Days_Formula__c, CW_in_Last_30_Days_Workflow__c, CW_in_Last_730_Days_Formula__c, CW_in_Last_730_Days_Workflow__c from Opportunity Where StageName = \'S8- Closed Won\' AND Software_Product_Count__c > 0 AND ( ((CW_in_Last_30_Days_Formula__c = True AND CW_in_Last_30_Days_Workflow__c = False) OR (CW_in_Last_30_Days_Formula__c = False AND CW_in_Last_30_Days_Workflow__c = True)) OR ((CW_in_Last_730_Days_Formula__c = True AND CW_in_Last_730_Days_Workflow__c = False) OR (CW_in_Last_730_Days_Formula__c = False AND CW_in_Last_730_Days_Workflow__c = True)) )';
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<Opportunity> batch){
lstOpp = new List<Opportunity>();
for(Opportunity objOpp : batch){
if(objOpp.CW_in_Last_30_Days_Formula__c == True) {
objOpp.CW_in_Last_30_Days_Workflow__c = True;
}
else{ //if(objOpp.CW_in_Last_30_Days_Formula__c == False){
objOpp.CW_in_Last_30_Days_Workflow__c = False;
}
if(objOpp.CW_in_Last_730_Days_Formula__c == True) {
objOpp.CW_in_Last_730_Days_Workflow__c = True;
}
else{ //if(objOpp.CW_in_Last_730_Days_Formula__c == False) {
objOpp.CW_in_Last_730_Days_Workflow__c = False;
}
lstOpp.add(objOpp);
}
Database.SaveResult[] dbOppList = Database.Update(lstOpp, false);
// System.debug('Update CW ' + dbOppList[].Id);
for(Database.SaveResult sr : dbOppList) {
if(sr.isSuccess()) {
// Operation was successful, so get the ID of the record that was processed
System.debug('Successfully Updated OPP ID: ' + sr.getId());
}
else {
// Operation failed, so get all errors
for(Database.Error err : sr.getErrors()) {
System.debug('The following error has occurred.');
System.debug(err.getStatusCode() + ': ' + err.getMessage());
System.debug('Users fields that affected this error: ' + err.getFields());
}
}
}
}
global void finish(Database.BatchableContext BC){
}
}
Thanks