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
Luca DebellisLuca Debellis 

Help with apex Batch ?

Implement a batch that counts the accounts and sends an email with the account number, thanks at all.
Best Answer chosen by Luca Debellis
ravi soniravi soni
hi luca,
try following apex Batch Class that sanding email.
public class sendEmailViaApexBatch implements Database.Batchable<SObject> {
    public static Integer noOfAccount = 0;
      public Database.QueryLocator start(Database.BatchableContext context) {
        return Database.getQueryLocator([select Id,AccountNumber from Account WHERE AccountNumber != null order by Name]);
    }
    public void execute(Database.BatchableContext context, List<Account> scope) {
        list<Account> lstAccount = (List<Account>) scope;
        noOfAccount = lstAccount.size();
        sendEmail();
        
    }
       public void finish(Database.BatchableContext BC){
        AsyncApexJob a = [SELECT Id, Status,ExtendedStatus,NumberOfErrors,JobItemsProcessed,TotalJobItems, CreatedBy.Email 
                          FROM AsyncApexJob WHERE Id =:BC.getJobId()];
           system.debug('a===> ' + a);
          }
    public static void sendEmail(){
           Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            List<String> sendTo = new List<String>();
           sendTo.add('test12345@gmail.com');
           mail.setToAddresses(sendTo);
           mail.setSubject('count Account Number ' );
           mail.setPlainTextBody('Total Account Number : ' + noOfAccount  );
           Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }

}

above class sanding No Of Accounts Where accountNumber != null
let me know if it helps you and marking it as best so that it can help to others.
Thank you

All Answers

ShivankurShivankur (Salesforce Developers) 
Hi Luca,

Batch Apex:
A Batch class allows you to define a single job that can be broken up into manageable chunks that will be processed separately.

Here is how to write sample Batch Apex:
1) Start method is automatically called at the beginning of the apex job. This method will collect record or objects on which the operation should be performed. These record are divided into subtasks & passes those to execute method.

2) Execute Method performs operation which we want to perform on the records fetched from start method.

3) Finish method executes after all batches are processed. Use this method to send confirmation email notifications.

Reference:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch.htm

The sample code would like below:
public class MyBatchable implements Database.Batchable<SObject> {

    public Database.QueryLocator start(Database.BatchableContext context) {
        return Database.getQueryLocator([select Id from Account order by Name]);
    }

    public void execute(Database.BatchableContext context, List<Account> scope) {
        Account[] updates = new Account[] {};
        for (AggregateResult ar : [
                select AccountId a, count(Id) c
                from Contact
                where AccountId in :scope
                group by AccountId
                ]) {
            updates.add(new Account(
                    Id = (Id) ar.get('a'),
                    No_of_Contacts__c = (Decimal) ar.get('c')
                    ));
        }
        update updates;
    }

    public void finish(Database.BatchableContext BC)
    {
        AsyncApexJob a = [Select Id, Status,ExtendedStatus,NumberOfErrors, JobItemsProcessed,TotalJobItems, CreatedBy.Email    from AsyncApexJob where Id =:BC.getJobId()];
      
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {Email to addresses};
        mail.setToAddresses(toAddresses);
        mail.setSubject('Account Number Email ');
        mail.setPlainTextBody('Account Number ' + a.Name);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}
To run the Batchable:
Database.executeBatch(new MyBatchable(), 50);
This Batch apex will count number of Contacts associated with Account object.It will store the count in a field "No_of_Contacts" on Account.And sends an email with provided email addresses with provided content.

Additional Reference:
http://amitsalesforce.blogspot.com/2016/02/batch-apex-in-salesforce-test-class-for.html

Hope above information helps, Please mark as Best Answer so that it can help others in the future.

Thanks.
ravi soniravi soni
hi luca,
try following apex Batch Class that sanding email.
public class sendEmailViaApexBatch implements Database.Batchable<SObject> {
    public static Integer noOfAccount = 0;
      public Database.QueryLocator start(Database.BatchableContext context) {
        return Database.getQueryLocator([select Id,AccountNumber from Account WHERE AccountNumber != null order by Name]);
    }
    public void execute(Database.BatchableContext context, List<Account> scope) {
        list<Account> lstAccount = (List<Account>) scope;
        noOfAccount = lstAccount.size();
        sendEmail();
        
    }
       public void finish(Database.BatchableContext BC){
        AsyncApexJob a = [SELECT Id, Status,ExtendedStatus,NumberOfErrors,JobItemsProcessed,TotalJobItems, CreatedBy.Email 
                          FROM AsyncApexJob WHERE Id =:BC.getJobId()];
           system.debug('a===> ' + a);
          }
    public static void sendEmail(){
           Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            List<String> sendTo = new List<String>();
           sendTo.add('test12345@gmail.com');
           mail.setToAddresses(sendTo);
           mail.setSubject('count Account Number ' );
           mail.setPlainTextBody('Total Account Number : ' + noOfAccount  );
           Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }

}

above class sanding No Of Accounts Where accountNumber != null
let me know if it helps you and marking it as best so that it can help to others.
Thank you
This was selected as the best answer
Luca DebellisLuca Debellis
Thank you very much for your answers, they were very helpful. How do you even schedule a batch? In this case for example.