+ 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:

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;

   global void finish(Database.BatchableContext BC){
       AsyncApexJob a = 
           [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,
            TotalJobItems, CreatedBy.Email
            FROM AsyncApexJob WHERE Id =
       // 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.setSubject('Record Clean Up Status: ' + a.Status);
       ('The batch Apex job processed ' + a.TotalJobItems +
       ' batches with '+ a.NumberOfErrors + ' failures.');
       Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });