Scheduled Apex in Salesforce: Where, When, and How to Apply It Best?

Scheduled Apex in Salesforce: Where, When, and How to Apply It Best?

Salesforce is a powerful platform that allows automating business processes, but sometimes there is a need to perform certain operations on a schedule. This is where Scheduled Apex comes into play — a tool that allows running Apex code at a specified time or on a regular schedule. In this article, we will explore what Scheduled Apex is, when it should be used, and how to use it correctly.

What is Scheduled Apex?

Scheduled Apex is a mechanism in Salesforce that allows developers to schedule the execution of Apex code at a specific time or with a certain frequency (e.g., hourly, daily, weekly, or monthly).

This is done using the Schedulable interface, which is implemented in an Apex class. After creating such a class, it can be scheduled through the Salesforce interface or programmatically via System.schedule.

Example of a simple Scheduled Apex class:

global class UpdateOldAccountsJob implements Schedulable {
    global void execute(SchedulableContext sc) {
        
        List<Account> accounts = [SELECT Id, Name, Description 
                                 FROM Account 
                                 WHERE LastModifiedDate < LAST_N_DAYS:30];
        
        if (accounts != null && !accounts.isEmpty()) {
            for (Account acc : accounts) {
                acc.Description = 'Updated via Scheduled Apex';
            }
            update accounts;
        }
    }
}        

To schedule this class, for example, to run daily at 2 AM, you can use the following code in the Anonymous Window:


String cronExp = '0 0 2 * * ?'; // Every day at 02:00
System.schedule('Daily Account Update', cronExp, new MyScheduledJob());        

Here, cronExp is a CRON expression that defines the schedule.

Where to use Scheduled Apex?

Scheduled Apex is ideal for tasks that need to be performed regularly or at a specific time without user involvement. Here are a few use case scenarios:

  1. Data Updates For example, you can update outdated records, add tags to objects that haven't changed for a certain period, or synchronize data with external systems.
  2. Report Automation Scheduled Apex can generate reports or aggregated data and send them to users via email using Messaging.SingleEmailMessage.
  3. Data Cleanup Removing outdated records (such as temporary data or logs) on a schedule.
  4. Periodic Business Processes For example, calculating bonuses for employees at the end of the month or sending reminders to clients about subscription expiration.
  5. Integration with External Systems If you need to regularly retrieve or send data to an API, Scheduled Apex can be a convenient solution.

When is it better to use Scheduled Apex?

To make the most effective use of Scheduled Apex, follow these recommendations:

  1. Optimize SOQL queries Avoid excessive queries and use conditions in WHERE to reduce the volume of data. For example:

List<Contact> contacts = [SELECT Id, Email FROM Contact WHERE Email != null LIMIT 5000];        

2. Use Batch Apex for large data volumes If you need to process more than 10,000 records, run Batch Apex with Scheduled Apex:

global class ScheduleBatch implements Schedulable {
    global void execute(SchedulableContext sc) {
        Database.executeBatch(new MyBatchClass());
    }
}        

3. Add logging Create records in a custom object to track task execution. This will help diagnose issues.

4. Test the schedule Before deploying to production, validate the CRON expression for correctness using tools like crontab.guru.

5. Avoid conflicts Ensure that multiple Scheduled Apex jobs do not run simultaneously if they are working with the same data to prevent record locking.

6. Monitor limits Salesforce allows up to 100 active jobs to be scheduled concurrently. Monitor this in Setup > Apex Jobs.

Advantages and Limitations

Advantages:

  • Easy to configure via UI or code.
  • Flexibility in scheduling with CRON expressions.
  • Integration with other asynchronous processes (Batch, Queueable).

Limitations:

  • Not suitable for real-time processing.
  • Limit on the number of jobs (100 active).
  • Need to consider Salesforce governor limits.

Conclusion

Scheduled Apex is a powerful tool for automating regular tasks in Salesforce. It is perfect for updating data, generating reports, or scheduling integrations. From simple tasks, such as automatically wishing customers a happy birthday, to more complex ones like processing large volumes of data, synchronizing with other systems, or performing periodic updates — all of this can be achieved using Scheduled Apex. With the ability to configure execution frequency, this tool allows for easy scheduling and automation of business processes, reducing the need for manual intervention and improving Salesforce workflow efficiency.

要查看或添加评论,请登录

Mykhailo Vdovychenko的更多文章