I have created a Batch which is supposed to pull Completed tasks and Reopen them. It's a simple implementation (code attached), but what i observe is the Query is taking too long and ultimately aborts the batch.
I am not able to figure out what's causing this query to fail/take too long. Any help is appreciated!
public class ReopenReferralTasksBatch implements Database.Batchable<sObject>,Database.Stateful {
public Database.QueryLocator start(Database.BatchableContext BC){
String TASK_QUERY = 'SELECT Status FROM Task WHERE Status = \'Completed\' AND Type = \'Referral Enquiry\'';
TASK_QUERY += ' AND Referral_Reopen_Date__c = TODAY';
return Database.getQueryLocator(TASK_QUERY);
}
public void execute(Database.BatchableContext BC, List<Task> tasksToBeReOpened){
List<Task> reOpenedTasks = new List<Task>();
for(Task task : tasksToBeReOpened){
task.Status = 'Open';
reOpenedTasks.add(task);
}
if(reOpenedTasks.size()>0){
Database.SaveResult[] saveResultList = database.update(reOpenedTasks);
Integer index = 0;
for(Database.SaveResult svrslt : saveResultList){
if(!svrslt.isSuccess()){
String errMsg = svrslt.getErrors()[0].getMessage();
errorMap.put(reOpenedTasks[index].Id, errMsg);
}
else{
String sucMsg = baseURL + '/' + reOpenedTasks[index].Id;
successMap.put(reOpenedTasks[index].Id, sucMsg);
IdToSObjectMap.put(reOpenedTasks[index].Id, reOpenedTasks[index]);
}
index++;
}
}
}
public void finish(Database.BatchableContext BC){
WHJ_BatchMailHandler.Sendmail(IdToSObjectMap, errorMap, successMap, 'ReopenReferralTasksBatch');
}
}
Not just that, if a run the following query in dev console, it times out:
SELECT Status,Referral_Reopen_Date__c FROM Task WHERE Status = 'Completed'
Edit: Batch Size: executing with no explicit batch size from anonymous window.
Start method is the one where this limit is exceeded.
Referral_Reopen_Date__c : is a date type field.
If i add a today clause (Referral Reopen Date = Today) in the following:
SELECT Status,Referral_Reopen_Date__c FROM Task WHERE Status = 'Completed'
It still times out on the QUERY stating: It's taking too long!
querylocator
then you can limit it to some 20 millions (or any number based on your testing) and then chain the batch in finish method again to run for another 20 million. Fire the email only when there is nothing to process.LAST_N_DAYS:30
creates a filter cap on your data to fetch only last 30 days of tasks, so your query result is returned under those 2 minutes.