top of page
Writer's pictureA. Agrawal

How to schedule a job for more than 12 months in Salesforce

 



In Salesforce, when using Schedule Apex, the limitation of scheduling a job only for up to 12 months can be restrictive for certain business requirements. To overcome this issue, it is recommended to store the interval of months in a custom field. This approach involves creating a custom field on a suitable object to capture the desired interval for job scheduling. By doing so, you can programmatically reference this interval and dynamically schedule the Apex job accordingly. This method provides flexibility and ensures that your scheduled jobs can accommodate more extended periods beyond the default 12-month limitation, thus better aligning with your business needs.


In this blog, I will guide you through the process of overcoming the 12-month scheduling limitation in Salesforce's Schedule Apex by leveraging a custom field to store the interval of months. 


By creating a custom field to capture the desired scheduling interval, we can dynamically reference this field in our Apex code to schedule jobs for extended periods beyond the default limit. This approach ensures greater flexibility and allows your scheduled jobs to better meet your long-term business requirements. Follow along as I provide step-by-step instructions to implement this solution and enhance your Salesforce scheduling capabilities.


Step 1: Create Custom Setting

  • Enable Manage list custom setting type from Schema Settings

  • Create Custom Setting 

  •  Create a Custom Field with Date Datatype

    • Navigate to the object where you want to store the scheduling information.

    • Click on the "Custom Settings" section.

    • Click "New" to create a new custom field.

    • Select "Date" as the datatype and click "Next."

    • Enter a field label, such as "Last Run Date."

    • Optionally, enter a field name and description.

    • Set the necessary field-level security and add the field to the appropriate page layouts.

    • Click "Save" to create the field.


This field will be used to store the date when the scheduled job will run next.

  •  Create a Custom Field with Number Datatype

    • In the same object, click "New" to create another custom field.

    • Select "Number" as the datatype and click "Next."

    • Enter a field label, such as "Month Interval"

    • Optionally, enter a field name, and description, and specify the number of decimal places if needed.

    • Set the necessary field-level security and add the field to the appropriate page layouts.

    • Click "Save" to create the field.

This field will be used to store the interval (in months) at which the job should be scheduled (e.g., 21 months).


Step 2 - Create a Schedule Apex class

  • This scheduled Apex class is designed to run every month. Each time it is invoked, it checks the specified month interval criteria using the monthsBetween() method, which compares the current date to the last run date. If the criteria are satisfied and the interval matches the value stored in the custom field, the job will execute. 

  • This approach ensures that the job runs at precise intervals, providing a reliable solution for scheduling tasks in Salesforce beyond the default 12-month limit. By automating this process, you can efficiently manage long-term job scheduling according to your business needs.


DataDeletionSchedule Class

public with sharing class DataDeletionSchedule implements Schedulable {

    List<Account> accounts;

    public DataDeletionSchedule(List<Account> accounts) {

        this.accounts = accounts;

    }

    public void execute(SchedulableContext sc) {

        ScheduleDelete__c lastSchedule;

          try {

            lastSchedule = ScheduleDelete__c.getInstance('Delete Schedule');

        }

 catch(Exception e) {

            e.getMessage();

        }

        if(lastSchedule.LastRunDate__c == null) {

         AccountDomain.deleteAccounts(accounts);

            lastSchedule.LastRunDate__c = Date.today();

            ScheduleDeleteDomain.updateScheduleDelete(

                new List<ScheduleDelete__c>{lastSchedule}

            );

        }

        else {

            if(Date.today().monthsBetween(lastSchedule.LastRunDate__c) == lastSchedule.MonthInterval__c) {

                 AccountDomain.deleteAccounts(accounts);

                lastSchedule.LastRunDate__c = Date.today();

                ScheduleDeleteDomain.updateScheduleDelete(

                 new List<ScheduleDelete__c>{lastSchedule}

                 );

            }

        }

    }

}

ScheduleDeleteDomain Class

public with sharing class ScheduleDeleteDomain {

    public static void insertScheduleDelete(List<ScheduleDelete__c> lastSchedules) {

        if(lastSchedules.size() > 0) {

            insert lastSchedules;

        }

    }

    public static void updateScheduleDelete(List<ScheduleDelete__c> lastSchedules) {

        if(lastSchedules.size() > 0) {

            update lastSchedules;

        }

    }

}

AccountDomain Class

public class AccountDomain {

    public static List<Account> getAccountRecords() {

        return [

            SELECT

                Id,

                Name,

                Phone

            FROM

                Account

        ];

    }

    public static void deleteAccounts(List<Account> accounts) {

        if(accounts.size() > 0) {

            Delete accounts;

        }

    }

}

Step 3 - Create a Apex class

  • This class is designed to schedule a job to run every month. Each month, the class will check the specified interval criteria using the monthsBetween() method, which compares the current date to the last run date. If the criteria match the interval stored in the custom field, the job will be executed. 

  • This approach ensures that jobs are scheduled and executed at precise monthly intervals, providing a flexible and reliable solution for managing recurring tasks in Salesforce. By implementing this class, you can effectively handle long-term scheduling requirements that extend beyond the default 12-month limitation


DataDeletionController Class

public with sharing class DataDeletionController {

    public static void recordsToDelete(Integer scheduleInterval) {

        List<Account> accounts = AccountDomain.getAccountRecords();

        String expCron = '0 0 0 1  ? ';

        Id batchId = System.schedule(

            'Delete Schedule',

            expCron,

            new DataDeletionSchedule(accounts)

        );

        if(batchId != null) {

            ScheduleDelete__c lastSchedule;

             try {

            lastSchedule = ScheduleDelete__c.getInstance('Delete Schedule');

         }

            catch(Exception e) {

                e.getMessage();

            }

            if(lastSchedule != null) {

                lastSchedule.LastRunDate__c = null;

                lastSchedule.MonthInterval__c = scheduleInterval;

                ScheduleDeleteDomain.updateScheduleDelete(

                 new List<ScheduleDelete__c>{lastSchedule}

                 );

            }

            else {

                lastSchedule = new ScheduleDelete__c(

                    Name = 'Delete Schedule',

                    LastRunDate__c = null,

                    MonthInterval__c = scheduleInterval

                );

                ScheduleDeleteDomain.insertScheduleDelete(

                    new List<ScheduleDelete__c>{lastSchedule}

                );

            }

        }

    }

}

Explanation:

In this scheduling class, the monthsBetween() method is utilized to compare the current date with the last run date of the scheduled Apex class. This comparison determines if the specified month interval has elapsed. If the result matches the interval stored in the custom field, the job will execute accordingly. By using monthsBetween(), you can ensure that the job runs precisely at the required intervals, providing a robust solution for managing and scheduling Apex jobs beyond the standard 12-month limitation. This method enhances the precision and reliability of your scheduled tasks in Salesforce.


Conclusion

In conclusion, by storing the interval of months in a custom field and utilizing this field in your Apex code, you can effectively bypass the 12-month scheduling limitation in Salesforce's Schedule Apex. This approach provides enhanced flexibility and allows for long-term job scheduling that aligns with your business needs. Implementing this solution ensures that your scheduled jobs can be managed more efficiently and dynamically, ultimately improving your overall Salesforce automation processes.


If you'd like to see the code and resources used in this project, you can access the repository on GitHub.To access the AVENOIRBLOGS repository, click here. Feel free to explore the code and use it as a reference for your projects.


Thank You! You can leave a comment to help me understand how the blog helped you. If you need further assistance, please contact us. You can click "Reach Us" on the website and share the issue with me.


Reference 



Blog Credit:

A. Agrawal

Salesforce Developer

   Avenoir Technologies Pvt. Ltd.

  Reach us: team@avenoir.ai

Recent Posts

See All

Kommentare


bottom of page