You need to sign in to do that
Don't have an account?
Rohit 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.
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.
Batch - http://www.infallibletechie.com/2012/05/batch-apex.html
Schedulable class - http://www.infallibletechie.com/2012/05/apex-scheduler.html
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);