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
HoysalaHoysala 

Batch class to retrieve calls with status Draft from last 2 days and change the status to submitted. Anyone please help

Khan AnasKhan Anas (Salesforce Developers) 
Hi Suraj,

Greetings to you!

Below is the sample code which I have tested in my org and it is working fine. Kindly modify the code as per your requirement.
 
global class Batch_UpdateStatus implements Database.Batchable<sObject >{
    
    global Database.queryLocator start(Database.BatchableContext bc){
        return Database.getQueryLocator('Select Id, Status__c from Opportunity where Status=\'Draft\' AND LastModifiedDate = LAST_N_DAYS:2');
    }
    
    global void execute(Database.BatchableContext bc, List<Opportunity > scope){
        List<Opportunity> oppLst = new List<Opportunity>();
        for(Opportunity opp : scope){ 
            opp.Status__c = 'Submitted';
            oppLst.add(opp);
        }       
        UPDATE oppLst; 
    }
    
    global void finish(Database.BatchableContext bc){
    }
}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
HoysalaHoysala
Thanku so much Khan Anas. Its working perfectly now. 
HoysalaHoysala
Hi Khan Anas, in finish method i have to write code for email i.e., whenever batch job is completed we need to get the email saying no of records success and no of records failed. How can this be done? 
 
Khan AnasKhan Anas (Salesforce Developers) 
Try this:
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('Apex Sharing Recalculation ' + a.Status);
        mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems +
                              ' batches with '+ a.JobItemsProcessed + 'success,' + a.NumberOfErrors + ' failures.');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }

Regards,
Khan Anas