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
Kunal Purohit 4Kunal Purohit 4 

How to write Batch Apex code?

Hello Team,
I want to write batch Apex for sending mail with Total_paper_Count field. It is a custom field in Account Object. Please help
ANUTEJANUTEJ (Salesforce Developers) 
Hi Kunal,

I found this below implementation for sending a mail from the final method after a business logic is executed in the execute method, I hope this helps and you will have to invoke the batch apex or schedule the batch apex, I hope this helps and in case if this comes in handy can you please mark this as best answer so that it can be used by others in the future.
 
public class OwnerReassignment implements Database.Batchable<sObject>{
String query;
String email;
Id toUserId;
Id fromUserId;

public Database.querylocator start(Database.BatchableContext BC){
            return Database.getQueryLocator(query);}

public void execute(Database.BatchableContext BC, List<sObject> scope){
    List<Account> accns = new List<Account>();

   for(sObject s : scope){Account a = (Account)s;
        if(a.OwnerId==fromUserId){
            a.OwnerId=toUserId;
            accns.add(a);
            }
        }

update accns;
    
}
public void finish(Database.BatchableContext BC){
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

mail.setToAddresses(new String[] {email});
mail.setReplyTo('batch@acme.com');
mail.setSenderDisplayName('Batch Processing');
mail.setSubject('Batch Process Completed');
mail.setPlainTextBody('Batch Process has completed');

Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}

>> Link: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm

Regards,
Anutej​​​​​​​