Fetch records matching today’s date and update them daily using Apex in Salesforce?

Fetch records matching today’s date and update them daily using Apex in Salesforce?

AccountEffectiveBatch – Batch class to fetch Account records matching effectiveDate.

AccountEffectiveBatchSchedule – Scheduler to call schedule it daily. This will call the AccountEffectiveBatch class and pass today’s date.

AccountEffectiveBatchSchedule is scheduled to run daily at 10 PM until 27th August 2030.

1. Create a Custom field with Data datatype in Account object.


2. Create the Batch Class.

global class AccountEffectiveBatch implements Database.Batchable<sObject> {
    global Date effectiveDate;
    global AccountEffectiveBatch( Date effectiveDate ) {
        this.effectiveDate = effectiveDate;
    global Database.QueryLocator start( Database.BatchableContext BC ) {
        /* Fetching all Accounts where Effective_Date__c date is matched
        format() Converts the date to the local time zone and returns the converted date as a formatted string using the locale of the context user.
        If the time zone cannot be determined, GMT is used.*/
        String query = ‘SELECT Id,Name FROM Account WHERE Effective_Date__c = ‘ + String.valueOf( effectiveDate );
        return Database.getQueryLocator( query );
    global void execute( Database.BatchableContext BC, List< Account > scope ) {
         /* Updating Accounts descrition */
         for ( Account a : scope ) {
             a.Description = ‘Updated on ‘ + DateTime.now().format();     
         update scope;
    global void finish( Database.BatchableContext BC ) {

3. Create the Scheduler Class.

/* Schedule class to schedule call the Batch class*/
global class AccountEffectiveBatchSchedule implements Schedulable {
    global void execute( SchedulableContext SC ) {
        /*Passing today date to the Batch Class
        Date.today() Returns the current date in the current user’s time zone.*/
        AccountEffectiveBatch obj = new AccountEffectiveBatch( Date.today() );
        Database.executeBatch( obj );

4. Schedule the Scheduler Class.


Test Class:

private class AccountEffectiveBatchTest {
    static testMethod void acctEffectTest() {
        Date dtToday = Date.today();
        Account acc =  new Account( Name = ‘Test’, Effective_Date__c = dtToday );
        insert acc;
        AccountEffectiveBatchSchedule obj = new AccountEffectiveBatchSchedule(); 
        obj.execute( null );
        acc = [ SELECT Id, Description FROM Account WHERE Id =: acc.Id ];
        system.assert( acc.Description.contains( String.valueOf( dtToday ) ) );



2 thoughts on “Fetch records matching today’s date and update them daily using Apex in Salesforce?

Leave a Reply