LaceySnr.com - Salesforce Development Posts by Matt Lacey

Taking Out the Trash

Posted: 2012-03-22

Heads up! Breaking my usual style momentarily, this post is really to assist advanced administrators as opposed to seasoned coders.

More than a few times I've seen a question asked (be it on Twitter, Force.com support sites or LinkedIn groups), regarding the mass deletion of records for a particular object. Oftentimes the enquiry is from a system administrator looking to keep things clean in their system. Of course there are several options here, such as scheduling a delete via data loader, but I often find a simple, schedulable batch can do the job with incredible ease.

The most basic form, for say, clearing all data from a particular custom object is:

global with sharing class CleanUpAllTheThings implements Database.Batchable<sObject>, Schedulable
{
    global void execute(SchedulableContext SC)
    {
        Database.executeBatch(new CleanUpAllTheThings());
    }
  
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        // no smarts here, no where clause, get EVERYTHING!
        return Database.getQueryLocator('select Id from MyCustomObject__c');
    }
  
    global void execute(Database.BatchableContext BC, List<sObject> scope)
    {
        delete scope;
    }
  
    global void finish(Database.BatchableContext BC)
    {
    }
  
    public static testmethod void TestThis()
    {
        MyCustomObject__c sTestRecord = new MyCustomObject__c();

        // here you'll need to make sure you're filling in
        // all required fields with valid data
        sTestRecord.Name = 'Testing Testing';
        insert sTestRecord;

        Test.startTest();
        System.Schedule('Testing', '0 0 1 1 1 ?', new CleanUpAllTheThings());
        Database.executeBatch(new CleanUpAllTheThings());
        Test.stopTest();

        System.Assert([select Id from MyCustomObject__c where Id = :sTestRecord.Id].size() == 0);
    }
}

You can then schedule this using the click path Setup -> Develop -> Apex Classes -> Schedule Apex:


Highlighted image showing the click path for scheduling an Apex job.

And then you can choose to run it when you desire, though through this particular interface the highest granularity is daily (achieved by choosing Weekly and then checking all of the days of the week):


The scheduling settings, here the clean up is scheduled to run at 10pm every Sunday until 2022.

The most complex part of this whole class is the test method, you have to be sure that you're inserting a valid record for the code to work with, which essentially means filling in valid values for the various required fields, otherwise you can pretty much treat this thing like a black box; there may be some aspects which are confusing if you've not got any development experience, but feel free to post any questions in the comments and I'll do my best to help.