function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Allan LorentzenAllan Lorentzen 

How to setup an automatic deletion of records in custom object?

I have two custom objects [access.log & trans.log] who receive daily updates [New Records] from an external system. After 31 days we don't need them anymore and we would like to delete them. Both objects have a date field on the record 'Log_date__c'.

I know that you can make a job that deletes these records on a daily basis.

My question;

- How do I write a code that deletes the right records? (Log_date__c older than 31 days)
- How/where do I put in SFDC? (Apex Class or Trigger! - Both!)

Are there any who can help me progress. In which case it will be my first code in SFDC.
Best Answer chosen by Allan Lorentzen
Prosenjit Sarkar 7Prosenjit Sarkar 7
Hi Allan,
These steps might be help full for you.
Create a schedulable apex class 
global class DeleteRecords implements Schedulable{
    global void execute(SchedulableContext SC) {
        List<Custom_Object__c> customObj = [select Id FROM Custom_Object__c WHERE createddate = LAST_N_DAYS:30];
        if(!customObj.isEmpty())
            delete customObj;
    }
}

 Now go to Setup -> Develop -> Apex classes . Click on Schedule Apex Button and schedule your apex like this 


User-added image

Select your preffered time (Time will be based on the users time zone) and Save.
Your job will run per month. You can check the status of your job by Setup -> Jobs -> Apex Jobs.

Thanks.
 

All Answers

Tavant TechnologiesTavant Technologies
Hi Allan,

You can use schedular class below is the link. Configure it to run on every 31st of the month.

In schedular class method  just have a query

Delete [Select id, .....  from access.log where createddate = LAST_N_DAYS:90 ] 

Trigger runs when a record is created , edited and so , but you need every month the deletion to happen.
So the schedular is the right one executing once in a month and deletes the record for last 31 days.

 
Sachin KadianSachin Kadian
Hi Allan,

For this you can write a Batch Job and schedule it to  execute everyday and will get all those reocrds where Log_date__c is older than 31 days and delete them.
Miika RintakoskiMiika Rintakoski
HI Allan,

Here is a detailed guide to scheduling Apex:

https://help.salesforce.com/apex/HTViewHelpDoc?id=code_schedule_batch_apex.htm

Hope it helps!

Miika
Allan LorentzenAllan Lorentzen
Yes - but how and where do I need to start in SFDC. I have never done this before. 
Tavant TechnologiesTavant Technologies
Go to Setup->Develop-> Apex Classes and click new .. Once you are done schedule it as mentioned in the document
Miika RintakoskiMiika Rintakoski
Hi Allan,

And to continue my previous post you could add new formula fieds to these custom objects (Deletable__c). The formula could be something like
TODAY() > Log_date__c + 31
 
List<Your_Object__c> toDelete = [SELECT Id FROM Your_Object__c WHERE Deletable__c == true];
delete toDelete;

Miika
Allan LorentzenAllan Lorentzen
Hi Tavant 

And the code I need to write? Is it 'Delete[Select id, from Access_logs__c where Access_logs__c=LAST_N_DAYS:31] ? 
 
Tavant TechnologiesTavant Technologies

Delete   [Select id, .....  from access.log where createddate < LAST_N_DAYS:31 ]      looks fine for your purpose
Allan LorentzenAllan Lorentzen
Hi Miika 

It seems like I am getting an error - I guess that there need be more content in my code;

User-added image
Prosenjit Sarkar 7Prosenjit Sarkar 7
Hi Allan,
These steps might be help full for you.
Create a schedulable apex class 
global class DeleteRecords implements Schedulable{
    global void execute(SchedulableContext SC) {
        List<Custom_Object__c> customObj = [select Id FROM Custom_Object__c WHERE createddate = LAST_N_DAYS:30];
        if(!customObj.isEmpty())
            delete customObj;
    }
}

 Now go to Setup -> Develop -> Apex classes . Click on Schedule Apex Button and schedule your apex like this 


User-added image

Select your preffered time (Time will be based on the users time zone) and Save.
Your job will run per month. You can check the status of your job by Setup -> Jobs -> Apex Jobs.

Thanks.
 
This was selected as the best answer
RajKumaR MRajKumaR M
Hi Allan,

Your code is not written in the complete format. It seem the logic is correct but need to follow some standards for apex class.

You might need to follow the basic apex class samples.

 
Allan LorentzenAllan Lorentzen
Hi Prosenjit 

I belive that you I would say that you have shown me the solution - a thousand thanks,
 
global class DeleteRecords implements Schedulable{
  global void execute(SchedulableContext SC){
      List<Access_logs__c> alObj = [select Id, Deletable__c FROM Access_logs__c WHERE Deletable__c = true];
    }
}

 
Prosenjit Sarkar 7Prosenjit Sarkar 7
Most welcome Allan
Jessica KellumJessica Kellum
Hello,

I'm trying to use this same code to automatically delete Cases with the Status as Closed as Duplicate. Similar scenario, wherein I haven't created anything in code. Will a similar piece of code work? If so, what would that look like?
Support DMLStreamSupport DMLStream
If anyone is reading this post and would like to avoid custom Apex triggers, here is an alternative approach to consider…

Step 1) Create a Workflow Rule with a Time Triggered (30 days after CreatedDate) Field Update setting an Expired__c checkbox = true.

Step 2) Since Workflow Rules nor Process Builder can delete records, use this new App in the AppExchange (DMLStream), which can handle virtually any DML operation with ease. It's also a managed package so it does not count against your org's SOQL/DML governor limits.

For this scenario, you would just set the Trigger Expression to ISCHECKED(Expired__c) with a Macro Type of Delete Record as shown below.  Done.  Problem solved with no deployments or hassles.

Here’s a little sneak peek into the DMLStream app…

DMLStream Macros can delete records, or even trigger off of record deletes to do other things.

Macros are simply records you create and activate.  Once configured, DMLStream requires no Setup Menu or Code Deployments to define your new automation scenarios. This means no additional technical debt for your org to maintain.

This example shows a Contact record delete macro whenever the "Not Interested" custom checkbox is checked:

DMLStream Example - Delete Record Macro


If you are seeking a good alternative to Flow and custom Apex triggers, visit the DMLStream AppExchange Listing Here:

https://appexchange.salesforce.com/appxListingDetail?listingId=a0N3A00000EcqkYUAR

And the DMLStream Admin Guide with "Quick Start" instructions is here:

https://appexchange.salesforce.com/servlet/servlet.FileDownload?file=00P3A00000boCchUAE

 
Edward Vazquez 5Edward Vazquez 5
What if you just wanted to delete the value of a certain field from a record and not the entire record? 
Robert WamboldRobert Wambold

Be aware that there are limits with how many rows can be deleted with Apex Code.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_gov_limits.htm

JaanuJaanu
How about test class for this one pls ? I am not able to find the apex class to schedule it.

global class DeleteRecords implements Schedulable{ global void execute(SchedulableContext SC) { List<Custom_Object__c> customObj = [select Id FROM Custom_Object__c WHERE createddate = LAST_N_DAYS:30]; if(!customObj.isEmpty()) delete customObj; } }