Below is an outline of a schedulable class I'm trying to deploy. The goal of the class is to keep all tasks created in last 30 days, and, if there are no tasks in the last 30 days to keep only the most recent one.
I'm getting the following error on schedule (and in developer console), due to too many IDs in queries:
Aggregate query does not support
queryMore()
, useLIMIT
to restrict the results to a single batch.
global class TaskRetention implements Schedulable
{
global void execute(SchedulableContext SC)
{
AggregateResult[] tasksWithin30Days = [Select whatId from task where createddate = Last_n_days:30 group by whatid];
AggregateResult[] noTask30Days = [Select whatId,max(createddate) maxdate from task group by whatid having max(createddate) < Last_n_days:30 ];
Id[] hasTaskWithin30Days = new Id[]{};
Id[] noTasksIn30Days = new Id[]{};
String[] whatIdDateTimeList = new String[]{};
for(AggregateResult ar: tasksWithin30Days ){
hasTaskWithin30Days.add((Id)ar.get('whatId'));
}
for(AggregateResult ar: noTask30Days){
noTasksIn30Days.add((Id)ar.get('whatId'));
whatIdDateTimeList.add(''+ar.get('whatId')+ar.get('maxdate'));
}
delete [ Select Id from Task where whatId in :hasTaskWithin30Days and createddate< last_n_days:30];
delete [Select Id from Task where whatId in :noTasksin30Days and whatId_createddate__c not in :whatIdDateTimeList];
}
}
I can limit the results to 2k, but this renders the class ineffective (Perhaps not with Database.Stateful
?). I've read of using QueryMore
as a workaround, referencing last returned whatID perhaps? I've also seen references to iterable interfaces and @read, but I don't know how to employ either of those.