Apex Job to delete records

Published in Articles

I think, more than once you had a task of regular cleaning up obsolete or unnecessary records. I advise you a simple solution, that allows you to schedule this process. Please note that this solution is only available for Enterprise, Unlimited and Developer editions.

public with sharing class DeleteRecordsJob implements Database.Batchable<sObject>, Schedulable {
  private final String query;
  
  public DeleteRecordsJob(String query) {
    this.query = query;
  }
  
  // Schedulable method
  public void execute(SchedulableContext ctx) {
    Database.executeBatch(new DeleteRecordsJob(query));
  }
  
  // Database.Batchable methods
  public Database.QueryLocator start(Database.BatchableContext bc) {
    return Database.getQueryLocator(query);
  }
  
  public void execute(Database.BatchableContext bc, List<sObject> scope) {
    delete scope;
  }
  
  public void finish(Database.BatchableContext bc) {
  }
}

There is an example of a batch job that deletes accounts that do not has any activities in the last 5 years.
DeleteRecordsJob j = new DeleteRecordsJob('SELECT ID FROM Account WHERE LastActivityDate < LAST_N_YEARS:5');
Database.executeBatch(j);

It's also easy to schedule the job. Here's an example of a schedule job, which deletes all the converted leads every Saturday.
DeleteRecordsJob j = new DeleteRecordsJob('SELECT ID FROM Lead WHERE IsConverted = TRUE');
System.schedule('Delete Converted Leads', '0 0 0 ? * SAT *', j);

This class is ready for use in production code, but before this, I recommend you to make some modifications:

Useful links:

Comments powered by CComment