This is the sample batch class that I am working on. This class is working fine but I need to add one more condition like, If status is set to submitted after 2PM, The number field should not be increased. But the batch job runs everyday at 3PM, So that record should be increased in next day run. How to achieve that? Any help would be appreciated. TIA.
global class BatchCounter implements Database.Batchable<sObject> {
static final String businessHoursId;
global Database.QueryLocator start(Database.BatchableContext bc) {
String query = 'SELECT Id, numberField__c,statusField__c,Submitteddate__c FROM objectName__c WHERE Submitteddate__c !=null '+' AND statusField__c IN (\'Assigned\', \'Submitted\', \'InProgress\')';
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext bc, List<TMA__c> tmas) {
for (TMA__c tma : tmas) {
if (isBusinessHours(businessHoursId)) {
tma.numberField__c+=1;
}
}
update tmas;
}
global void finish(Database.BatchableContext bc) {
}
private static Boolean isBusinessHours(Id businessHoursId) {
BusinessHours businessHours = [SELECT Id FROM BusinessHours WHERE Id = :businessHoursId];
if (businessHours != null) {
Datetime currentDatetime = Datetime.now();
return BusinessHours.isWithin(businessHoursId, currentDatetime);
}
return false;
} }
I have modifed the execute method like below, To capture the record which is submitted after 2pm EST On Monday and exclude it in Monday's 3pm EST batch run.
global void execute(Database.BatchableContext bc, List<TMA__c> tmas)
{ Datetime today = Datetime.now().date();
Datetime cutoffEnd= Datetime.newInstance(today.year(),today.month(),today.day(),14,0,0);
for (TMA__c tma : tmas) {
if(tma.status__c =='Submitted" && tma.submitteddate__c>cutoffEnd)
{ continue; }
if (isBusinessHours(businessHoursId))
{ tma.numberField__c+=1;
}}
update tmas;
}
It excluded the 2 records as expected on Monday and updated all other records. But it should have updated these 2 records in yesterday's batch run , but it didn't. Batch updated all other records and excluded these 2 in yesterday's run which is not correct. What am I doing wrong? Please send some help here.