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
mxravimxravi 

Unable to process more than one batch. Need Help! Urgent!

Unable to process more than one batch. Please help. Here is the code. 

 

global class ICG_Opportunity_Disp_App_Booked implements Database.Batchable<sObject> {

global string query = null;
global string clause='';
global Boolean calledByTestClass = false;
global Datetime startDate;
global Datetime endDate;
global Datetime testdate;
global list<string> op_List = new list<string>();
// global list<string> products = new list<string>();

global ICG_Opportunity_Disp_App_Booked (){
ApexClass apexClass = [SELECT Name, Id FROM ApexClass where name = 'ICG_Opportunity_Disp_App_Booked'];
//AsyncApexJob asyncApexJob =[SELECT Id, ApexClassId, CompletedDate, JobType, Status FROM AsyncApexJob where ApexClassId=:apexClass.Id order by CompletedDate desc limit 1];
setStartEndDate();
// disposition();
// productcategory();

if(startdate!=NULL && enddate!=NULL){
system.debug('startdate:'+startdate);
system.debug('enddate:'+enddate);

op_list.add('Application booked');
op_list.add('Application in progress');
op_list.add('Application Approved');
op_list.add('Entered in Net Oxygen');
op_list.add('Application Entered');
system.debug('Op_list @@@@@@@@ ' +op_list);


query = 'select accountid,Product_Category__c,StageName,createddate FROM Opportunity where createddate >=:startdate AND createddate <=:enddate AND stagename IN :op_list';

}else{
//testdate = asyncApexJob.CompletedDate;
system.debug('testdate:'+testdate);
query = 'select accountid,Product_Category__c,stageName,createddate FROM Opportunity where createddate >=:testdate AND stagename IN :op_list';
}

system.debug('Query:'+query);
}


global private void setStartEndDate(){
Job_scheduler__c jobSchedulerSettings = Job_scheduler__c.getInstance('Date_Range_Oppty');
startdate = jobSchedulerSettings.Start_date__c;
enddate = jobSchedulerSettings.End_date__c ;
}

// Global method - start

global Database.QueryLocator start(Database.BatchableContext BC){
if(calledByTestClass) {
query +=' limit 200';
System.debug('query value: ' +query );
}
system.debug('Query:'+query);
return Database.getQueryLocator(query);
}

// Global method - execute

global void execute(Database.BatchableContext BC, List<sObject> scope){
system.debug('Executing...');
Map<ID,Set<String>> AccMap = new Map<ID,Set<String>>();
Map<String,Opportunity> AccMap2 = new Map<String,opportunity>();
try{
for(Sobject s: scope){
Opportunity custPros= new Opportunity ();
custPros = (Opportunity)s;


if(!(AccMap.containsKey(custPros.accountid))) {
Set<String> temp1 = new SET<String>();
//Date temp2;
//DateTime testdate = custPros.CreatedDate;
String key = custPros.accountid+'-'+custPros.Product_Category__c;
temp1.add(custPros.Product_Category__c);
//temp2= custPros;
AccMap.put(custPros.accountid,temp1);
AccMap2.put(key,custPros);
}else {
Set<String> temp = AccMaP.get(custPros.AccountId);
//Date temp2;
String key = custPros.accountid+'-'+custPros.Product_Category__c;
temp.add(custPros.Product_Category__c);
system.debug('this is the date we have a prob'+custPros.CreatedDate.date());
//temp2 = custPros.CreatedDate.date();
AccMap.put(custPros.accountid,temp);
AccMap2.put(key,custPros);
}

}
}Catch(Exception e){
System.debug('Preparing the Key Map Logic'+e);
}
List<Customer_Product__c> cpList = new list<Customer_Product__c>();
try{
cpList= [SELECT id,customer_Prospect__c,Product__r.Product_Category_Desc__c,CreatedDate FROM Customer_Product__c where Customer_prospect__c In:AccMap.keySet() order by createddate desc];
system.debug('Size of CP list'+cpList.size());

}Catch(Exception e){
System.debug('Customer Products Query'+e);
}

set<Opportunity> Opps= new set<Opportunity>();
list<opportunity> updateopps = new list<opportunity>();

String keyMatch;

try{
for(Customer_Product__c cp: cpList){
if(AccMap.containsKey(cp.customer_prospect__c)){
keymatch = cp.customer_prospect__c+'-'+cp.product__r.product_category_desc__c;
system.debug('KeyMatch' +keymatch);
if(AccMap2.get(keymatch)!= NULL) {
Opportunity opp = AccMap2.get(keyMatch);

if(!(opps.contains(opp))){
system.debug('OPP@@@@@@@@ ' +opp);
if(cp.createddate>opp.createddate){

opp.StageName='Application Booked';
system.debug('Created Date' +cp.createddate);
opp.CloseDate = cp.CreatedDate.date();
opps.add(opp);
system.debug('Opp..............'+opps);
}
}
}
}
}

system.debug('set of opportunities' +opps);
for(opportunity unique_op: opps){
updateopps.add(unique_op);
}
system.debug('List of opportunities' +updateopps);

}Catch(Exception e){
System.debug('Looping Customer products'+e);
}


if(UpdateOpps.size() > 0){
Database.update(UpdateOpps,false);
}
}


global void finish(Database.BatchableContext BC){
// Get the ID of the AsyncApexJob representing this batch job
// from Database.BatchableContext.
// Query the AsyncApexJob object to retrieve the current job's information.

AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed,TotalJobItems, CreatedBy.Email
from AsyncApexJob
where Id =:BC.getJobId()];

// Send an email to the Apex job's submitter notifying of job completion.
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {a.CreatedBy.Email};
mail.setToAddresses(toAddresses);
mail.setSubject('Apex Opportunity update ' + a.Status);
mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems +' batches with '+ a.NumberOfErrors + ' failures.');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}

Best Answer chosen by Admin (Salesforce Developers) 
UVUV

You are setting limit of 200 in the query and by default batch process takes batch size of 200 records.

If you want to process more records then remove the limit or reduce the batch size by setting it explicitely.

All Answers

UVUV

You are setting limit of 200 in the query and by default batch process takes batch size of 200 records.

If you want to process more records then remove the limit or reduce the batch size by setting it explicitely.

This was selected as the best answer
mxravimxravi

Sorry Umesh, by mistake I clicked on accpet the answer. I am having a limit if it is a test class. 

 

At first 200 opportunities are taken as a batch and customer products are the queried. Customer products are more than opportunities. 

 

The First batch is processing perfectly fine. It is taking 200 opportunities and then querying the customer products and then updating the records. 

 

After that none of the batches are getting processed. This is happening only in production. In sanbox instance all the batches are getting processed without any issue. But the difference is in sandbox the amount of data is less than production. Its breaking in production. Please advice. 

 

Thank You

 

 

UVUV

Are you getting any error??? Job may get stuck somewhere if you are having huge number of records in the database..Since its asyncronus process and tough to debug I would suggest you to log a case with salesforce.

If the same code is working in the Sandbox then  they can see the status of your jobs using their internal tools...They would definately help you out...As a workaround you can try reducing the batch size..