Apex Class
public class InactiveAccountDeleter implements Database.Batchable<Account> {
private final Integer INACTIVE_THRESHOLD_MONTHS = 3;
public Iterable<Account> start(Database.BatchableContext context) {
Date currentDate = Date.today();
Date thresholdDate = currentDate.addMonths(-INACTIVE_THRESHOLD_MONTHS);
return [SELECT Id FROM Account WHERE LastActivityDate < :thresholdDate];
}
public void execute(Database.BatchableContext context, List<Account> accounts) {
Database.delete(accounts, false);
}
public void finish(Database.BatchableContext context) {
// Send an email notification to the administrator
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {'admin@example.com'};
email.setToAddresses(toAddresses);
email.setSubject('Inactive accounts have been deleted');
email.setPlainTextBody('All accounts inactive for more than ' + INACTIVE_THRESHOLD_MONTHS + ' months have been deleted.');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });
}
}
Apex Code
To schedule this batch Apex class to run at a specific time every day, you can use the System.schedule()
String cronExpression = '0 0 0 * * ?'; // Run every day at midnight
String jobName = 'InactiveAccountDeleter';
InactiveAccountDeleter batch = new InactiveAccountDeleter();
System.schedule(jobName, cronExpression, batch);
Video
Video does not exists.