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
Vivek DangateVivek Dangate 

In the batch apex, I want to send email if the 'count of record created today' is greater than 'the count of record created t yesterday'

In the batch apex, I want to send email if the 'count of record created today' is greater than 'the count of record created t yesterday'. Any help is really appreciated.
Best Answer chosen by Vivek Dangate
SwethaSwetha (Salesforce Developers) 
HI Vivek,

The below code is in context of account object. You can customize it for your custom object and get started
global class AccountRecordCountBatch implements Database.Batchable<sObject>, Database.AllowsCallouts {
    
global Database.QueryLocator start(Database.BatchableContext BC) {
    // Query for the count of Account records created today and yesterday
    Date today = Date.today();
    Date yesterday = today.addDays(-1);
    Integer todayCount = [SELECT COUNT() FROM Account WHERE CreatedDate = TODAY];
    Integer yesterdayCount = [SELECT COUNT() FROM Account WHERE CreatedDate = YESTERDAY];

    // Calculate the difference between the two counts
    Integer countDifference = todayCount - yesterdayCount;

    // If the difference is greater than zero, send an email
    if (countDifference > 0) {
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.setToAddresses(new List<String>{'abc@xyz.com'});
        email.setSubject('Account Record Count Alert');
        email.setPlainTextBody('The count of Account records created today is ' + todayCount 
            + ', which is greater than the count of Account records created yesterday (' + yesterdayCount + ') by ' 
            + countDifference + ' records.');
        Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{email});
    }

    // Return a null query locator to indicate that there are no records to process
    return Database.getQueryLocator([SELECT Id FROM Account WHERE CreatedDate = TODAY AND Id = null]);
}

    
    global void execute(Database.BatchableContext BC, List<sObject> scope) {
        // This method won't be called because there are no records to process
    }
    
    global void finish(Database.BatchableContext BC) {
        // This method won't be called because there are no records to process
    }
}

Make sure you are replacing with your email Id in the code

Run this code by using below snippet in dev console
AccountRecordCountBatch batch = new AccountRecordCountBatch();
Database.executeBatch(batch);



If this information helps, please mark the answer as best. Thank you

All Answers

SwethaSwetha (Salesforce Developers) 
HI Vivek,

The below code is in context of account object. You can customize it for your custom object and get started
global class AccountRecordCountBatch implements Database.Batchable<sObject>, Database.AllowsCallouts {
    
global Database.QueryLocator start(Database.BatchableContext BC) {
    // Query for the count of Account records created today and yesterday
    Date today = Date.today();
    Date yesterday = today.addDays(-1);
    Integer todayCount = [SELECT COUNT() FROM Account WHERE CreatedDate = TODAY];
    Integer yesterdayCount = [SELECT COUNT() FROM Account WHERE CreatedDate = YESTERDAY];

    // Calculate the difference between the two counts
    Integer countDifference = todayCount - yesterdayCount;

    // If the difference is greater than zero, send an email
    if (countDifference > 0) {
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.setToAddresses(new List<String>{'abc@xyz.com'});
        email.setSubject('Account Record Count Alert');
        email.setPlainTextBody('The count of Account records created today is ' + todayCount 
            + ', which is greater than the count of Account records created yesterday (' + yesterdayCount + ') by ' 
            + countDifference + ' records.');
        Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{email});
    }

    // Return a null query locator to indicate that there are no records to process
    return Database.getQueryLocator([SELECT Id FROM Account WHERE CreatedDate = TODAY AND Id = null]);
}

    
    global void execute(Database.BatchableContext BC, List<sObject> scope) {
        // This method won't be called because there are no records to process
    }
    
    global void finish(Database.BatchableContext BC) {
        // This method won't be called because there are no records to process
    }
}

Make sure you are replacing with your email Id in the code

Run this code by using below snippet in dev console
AccountRecordCountBatch batch = new AccountRecordCountBatch();
Database.executeBatch(batch);



If this information helps, please mark the answer as best. Thank you
This was selected as the best answer
Vivek DangateVivek Dangate
Hi Swetha,
I want to send a link for the list view of the object in the email. Is that possible. thank you in advance
SwethaSwetha (Salesforce Developers) 
@Vivek,
As the follow-up question is different from the original question posted, can you please post it as a new question for better tracking of efforts?

Also, please consider marking the provided answer as best to close the thread so it can help others too in the future.

Appreciate your understanding!
Thank you
Divya Agrawal 14Divya Agrawal 14
To achieve this using Salesforce Batch Apex, you can follow these steps:

1. Create a custom object to store the record counts for each day.
2. Create a batch class that retrieves the record count for the given object and compares it with the previous day's count.
3. Schedule the batch class to run daily.

Here's an example of the code:

Custom Object:
1. Create a custom object Daily_Record_Count__c with the following fields:
 - Date__c (Date, unique): The date when the record count was taken.
 - Record_Count__c (Number): The number of records created on the given date.

Batch Class:
Create a batch class that implements the Database.Batchable<sObject> and Database.Stateful interfaces.
 
global class RecordCountBatch implements Database.Batchable<sObject>, Database.Stateful {
    global Integer recordsToday = 0;
    global Integer recordsYesterday = 0;

    global Database.QueryLocator start(Database.BatchableContext bc) {
        Date today = Date.today();
        Date yesterday = today.addDays(-1);

        String query = 'SELECT Id, CreatedDate FROM YourCustomObject__c WHERE CreatedDate = TODAY OR CreatedDate = YESTERDAY';
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext bc, List<sObject> scope) {
        for(sObject s : scope) {
            YourCustomObject__c record = (YourCustomObject__c) s;
            Date createdDate = record.CreatedDate.date();
            if(createdDate == Date.today()) {
                recordsToday++;
            } else if(createdDate == Date.today().addDays(-1)) {
                recordsYesterday++;
            }
        }
    }

    global void finish(Database.BatchableContext bc) {
        if(recordsToday > recordsYesterday) {
            sendEmail(recordsToday, recordsYesterday);
        }
    }

    private void sendEmail(Integer recordsToday, Integer recordsYesterday) {
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {'your.email@example.com'};
        mail.setToAddresses(toAddresses);
        mail.setSubject('Record count comparison: Today vs Yesterday');
        mail.setPlainTextBody('Record count today: ' + recordsToday + '\nRecord count yesterday: ' + recordsYesterday);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}

Replace YourCustomObject__c with the API name of the object you want to monitor.

Schedule the Batch Class: Schedule the batch class to run daily using the System.schedule method or through the Salesforce UI.
 
String cronExp = '0 0 0 * * ?'; // Run daily at midnight
String jobName = 'Daily Record Count Comparison';
RecordCountBatch rcBatch = new RecordCountBatch();
System.schedule(jobName, cronExp, rcBatch);

If you find this useful, kindly consider selecting it as the Best Answer.

Thank you.
Divya Agrawal