+ Start a Discussion
SFDC Coder 8SFDC Coder 8 

Delete records using Batch Apex and store in CSV and send Email (Urgent)

Hi All,
I have one scnario like I want to write batch apex to delete records which are created more than 10 days ago in Task.
While deleting I want to store all records in CSV and want to send an Email to one Email-Id. (This also want to happen in Batch Apex)
How to write code for this?
Please help me.

Thanks in Advance
 
Aniket Malvankar 10Aniket Malvankar 10
Dear Coder,

You can go thro' article:
https://www.linkedin.com/pulse/salesforce-batch-apex-aniket-malvankar?published=t

Thanks
Aniket
Aniket Malvankar 10Aniket Malvankar 10
global class CleanUpRecords implements 
   Database.Batchable<sObject> {

   global final String query; 
   
   global CleanUpRecords(String q) {
       query = q; // You can write a query on TASK to get the old records
   }

   global Database.QueryLocator start(Database.BatchableContext BC){
 // add code to save the records in CSV
      return Database.getQueryLocator(query);
   }
   
   global void execute(
                Database.BatchableContext BC, 
                List<sObject> scope){
      delete scope;
      Database.emptyRecycleBin(scope);
   }

   global void finish(Database.BatchableContext BC){
       AsyncApexJob a = 
           [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,
            TotalJobItems, CreatedBy.Email
            FROM AsyncApexJob WHERE Id =
            :BC.getJobId()];
                          
       // Send an email to the Apex job's submitter 
       //   notifying of job completion. 
       Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
       String[] toAddresses = new String[] {a.CreatedBy.Email};
       mail.setToAddresses(toAddresses);
       mail.setSubject('Record Clean Up Status: ' + a.Status);
       mail.setPlainTextBody
       ('The batch Apex job processed ' + a.TotalJobItems +
       ' batches with '+ a.NumberOfErrors + ' failures.');
       Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
   }
}