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
Rohit Singh 68Rohit Singh 68 

Batch Apex to delete contact after 1 years of it's creation

Hi Experts,
I want to delete contacts automatically who’s created data are older than 2 years. I know it will be possible by Schedule Batch apex. Can you please help me with the code.
 
MagulanDuraipandianMagulanDuraipandian
Use batch and schedulable class.
Batch - http://www.infallibletechie.com/2012/05/batch-apex.html
Schedulable class - http://www.infallibletechie.com/2012/05/apex-scheduler.html
Paridhi Garg 1Paridhi Garg 1
Batch class is as follows:

global class ContactDeleteBatch implements Database.Batchable<sObject>{
    global Database.QueryLocator start (Database.BatchableContext bc){
        Date twoYearsBefore = Date.today().addYears(-2);
        return Database.getQueryLocator('Select id, createdDate from Contact where createdDate <= :twoYearsBefore');
    }
    
    global void execute(Database.BatchableContext bc, List<Contact> contactList){
       delete contactList;
    } 
    
    global void finish(Database.BatchableContext bc){
        
    }
}

Schedulable class for the batch is as follows:

global class ScheduleContactDeleteBatch implements Schedulable{
    global void execute(SchedulableContext sc) {
      ContactDeleteBatch contactDeleteBatchInstance = new ContactDeleteBatch(); 
      database.executebatch(contactDeleteBatchInstance);
   } 
}

You can schedule the batch using below mentioned code:
ScheduleContactDeleteBatch scheduleContactDeleteBatchInstance = new ScheduleContactDeleteBatch();
String sch = '20 30 8 10 2 ?'; //specify cron as per as your requirement
String jobID = system.schedule('Contact Deelete Batch', sch, scheduleContactDeleteBatchInstance);