Getting Started with Scheduled Apex in Salesforce

Understanding Scheduled Apex in Salesforce
Chinmaya By Chinmaya
6 Min Read

Introduction

If you’re new to Salesforce development, you might have heard of Scheduled Apex.

Scheduled Apex is an asynchronous way of processing records – that lets you run Apex code automatically at specific times, which is helpful for tasks you need to perform regularly, like data cleanup, email reminders, or batch data processing.

Let’s break down what Scheduled Apex is, how it works, and how you can use it with a simple example.

What is Scheduled Apex?

Scheduled Apex allows you to run your code at a scheduled time.
Think of it like setting an alarm or a timer for your code! Instead of running a piece of code manually, you can set it to run on a daily, weekly, or monthly basis, or even at very specific times.

This is particularly useful in scenarios where you want to:

    1. Perform regular maintenance tasks
    2. Process large amounts of data over time
    3. Send out automated notifications

How Scheduled Apex Works?

To use Scheduled Apex, you need to do 2 things:

    1. Create a Schedulable Apex Class
    2. Schedule the Apex Class

Step 1: Create a Schedulable Apex Class

The first step is to create a class that implements the Schedulable interface.
In Salesforce, an interface is a way of telling Salesforce that the class is special and can be scheduled.

Here’s a simple example:

				
					global class DataCleanupScheduler implements Schedulable {
    // The 'execute' method runs whenever the scheduler triggers this class
    global void execute(SchedulableContext sc) {
        // Put your code here - let's say we want to delete old records
        List<Account> oldAccounts = [SELECT Id FROM Account WHERE LastModifiedDate < LAST_N_DAYS:365];
        if (!oldAccounts.isEmpty()) {
            delete oldAccounts; // Deletes accounts that haven’t been updated in a year
        }
    }
}
				
			

In this example:

    1. DataCleanupScheduler is a global class that implements the Schedulable interface.
    2. The execute method contains the code we want to run at scheduled times.
    3. In this case, it finds and deletes old Account records that haven’t been modified in the last year.

Step 2: Schedule the Apex Class

Once your schedulable class is ready, you can schedule it in two ways:

1. Using the Salesforce UI

    1. Go to Setup > Apex Classes.
    2. Click on Schedule Apex.
    3. Choose your class (DataCleanupScheduler in this case).
    4. Set the schedule (e.g., every day at midnight).


2. Using Code

You can also schedule Apex with code by running a one-time execution in the Developer Console.
Here’s how:

The below code schedules the ‘DataCleanupScheduler’ class to run every day at 2:00 AM

				
					String cronExpression = '0 0 2 * * ?'; // At 2:00 AM every day
System.schedule('Daily Data Cleanup', cronExpression, new DataCleanupScheduler());
				
			

Here’s what’s happening:

cronExpression: This is a string that represents the schedule. Salesforce uses cron expressions to specify schedules.
In this example, ‘0 0 2 * * ?’ means “run at 2:00 AM every day.”

System.schedule: This method schedules the class to run based on the cronExpression.

CRON Expression Explained

Cron expressions look complex at first but are pretty straightforward once you know the format. Here’s the breakdown of the expression ‘0 0 2 * * ?’:

0: Seconds (0 in most cases)
0: Minutes (0 means at the top of the hour)
2: Hour (2 means 2 AM)
*: Day of the month (any day of the month)
*: Month (any month)
?: Day of the week (any day)

So, 0 0 2 * * ? runs the job every day at 2:00 AM.

Example Scenario: Daily Data Cleanup

Imagine you want to delete old accounts every day at 2:00 AM. Here’s how you’d set this up:

  1. Create the DataCleanupScheduler class (as shown above).
  2. Schedule it with Code:  Schedule to run every day at 2:00 AM

System.schedule(‘Daily Data Cleanup’, ‘0 0 2 * * ?’, new DataCleanupScheduler());

And that’s it! The DataCleanupScheduler will now run daily at 2 AM, checking for and deleting old accounts.

Managing Scheduled Jobs

To view or manage your scheduled jobs:

    1. Go to Setup > Scheduled Jobs.
    2. Here, you can see all scheduled jobs, including the ones created with code or through the UI.
    3. You can also delete jobs from this screen if they’re no longer needed.

Conclusion

Scheduled Apex is a powerful tool in Salesforce for automating routine tasks.
By scheduling an Apex class, you can keep your data organized, send reminders, or perform other regular maintenance without needing to run code manually.

Share This Article
Follow:
Chinmaya is working as a Senior Consultant with a deep expertise in Salesforce. Holding multiple Salesforce certifications, he is dedicated to designing and implementing cutting-edge CRM solutions. As the creator of Writtee.com, Chinmaya shares his knowledge on educational and technological topics, helping others excel in Salesforce and related domains.
Leave a comment