I have the following code that executes exactly how I need it to, the only issue is I receive "Apex CPU time limit exceeded" when I run the delete on Accounts, EmailMessage and update Cases. After looking into the error it looks like I need to move this code into a batch job however all of the documentation around batch jobs only ever delete one SObject. How can I execute this code in a batch job since I am looking at 3 SObjects?
The code basically deletes any accounts, cases and emailmessages that are over 30 days old. If the account has a new case then we ignore the old cases until that new case is 30 days old.
Date threshold = Date.today().addDays(-30);
List<Account> accountsToDelete = new List<Account>();
List<Case> casesToDelete = new List<Case>();
List<EmailMessage> messagesToDelete = new List<EmailMessage>();
Integer count = 0;
Integer count2 = 0;
Integer count3 = 0;
for (Account account : [
SELECT (SELECT LastModifiedDate FROM Cases ORDER BY LastModifiedDate DESC)
FROM Account WHERE Id IN (
SELECT AccountId FROM Case
WHERE LastModifiedDate < :threshold
AND Account.Name Like '%Test%'
)
]){
if (account.Cases[0].LastModifiedDate < threshold)
{
accountsToDelete.add(account);
casesToDelete.addAll(account.Cases);
}
}
messagesToDelete = [ SELECT Id, ParentId FROM EmailMessage WHERE ParentId IN : casesToDelete];
for(Case c: casesToDelete){
c.OwnerId = '005i0000001I5Y3';
c.Guest_Email__c = '';
c.Guest_Name__c = 'Purged';
}
for(Account a: accountsToDelete){
a.Id = '0018A000006Xvgo';
}
for(EmailMessage e: messagesToDelete){
e.FromAddress = '';
e.ToAddress = ''
}
update casesToDelete;
delete accountsToDelete;
delete messagesToDelete;