Skip to content

Schedule Apex in Salesforce: A Technical Guide for Developers

scheduled-apex

Apex is a programming language provided by Salesforce that allows developers to execute flow and transaction control statements on the Salesforce platform. Scheduled Apex is used to execute Apex code at a specific time or intervals. This tutorial will provide a detailed explanation of Schedule Apex in Salesforce, with code examples and step-by-step instructions.

Prerequisites

  1. A Salesforce Developer Edition (DE) account. Sign up here if you don’t have one.
  2. Basic knowledge of Apex programming in Salesforce.

Table of Contents

  1. Introduction to Schedule Apex
  2. Creating a Scheduled Apex Class
  3. Scheduling Apex Jobs
  4. Monitoring Scheduled Jobs
  5. Unscheduling Apex Jobs
  6. Best Practices

1. Introduction to Schedule Apex

Scheduled Apex is used to automate processes on a timely basis. You can schedule Apex code to run at specific intervals, such as every 15 minutes, hourly, daily, or weekly. Scheduled Apex is useful for automating tasks like generating reports, data cleanup, sending emails, or any other task that needs to be performed periodically.

2. Creating a Scheduled Apex Class

To create a Scheduled Apex class, you need to implement the Schedulable interface and define the execute method. The execute method is called when the scheduled job runs.

Here’s an example of a simple Scheduled Apex class that updates the LastModifiedDate field for all Account records every night:

global class UpdateAccountLastModifiedDate implements Schedulable {
    global void execute(SchedulableContext SC) {
        updateAccountsLastModifiedDate();
    }

    public void updateAccountsLastModifiedDate() {
        List<Account> accountsToUpdate = [SELECT Id FROM Account];
        
        for (Account acc : accountsToUpdate) {
            acc.LastModifiedDate = System.now();
        }
        
        update accountsToUpdate;
    }
}

In this example, the UpdateAccountLastModifiedDate class implements the Schedulable interface and defines the execute method, which in turn calls the updateAccountsLastModifiedDate method. The updateAccountsLastModifiedDate method retrieves all Account records and updates their LastModifiedDate field to the current date and time.

3. Scheduling Apex Jobs

To schedule an Apex job, you can either use the Salesforce UI or execute anonymous Apex code.

3.1 Using Salesforce UI

  1. Navigate to the Setup menu in Salesforce.
  2. Search for Apex Classes in the Quick Find box and click on it.
  3. Locate your scheduled Apex class and click on the Schedule Apex button next to it.
  4. Fill in the required information such as job name, start and end dates, preferred start time, and the frequency (daily, weekly, or monthly) of the job execution. Click Save.

3.2 Using Anonymous Apex Code

You can use the System.schedule method to schedule an Apex job programmatically. Here’s an example of how to schedule the UpdateAccountLastModifiedDate class to run daily at midnight:

UpdateAccountLastModifiedDate updateJob = new UpdateAccountLastModifiedDate();
String cronExpression = '0 0 0 * * ?';
String jobName = 'UpdateAccountLastModifiedDate_Daily';
System.schedule(jobName, cronExpression, updateJob);

The System.schedule method takes three parameters:

  1. jobName: The name of the job.
  2. cronExpression: The schedule for the job in the cron expression format. This expression, ‘0 0 0 * * ?’, means the job will run every day at midnight.
  3. schedulableClass: An instance of the Schedulable class.

4. Monitoring Scheduled Jobs

To monitor your scheduled jobs:

  1. Navigate to the Setup menu in Salesforce.
  2. Search for Scheduled Jobs in the Quick Find box and click on it.
  3. You’ll find a list of all scheduled jobs along with their status, next scheduled run, and other details.

5. Unscheduling Apex Jobs

To unschedule a job using Salesforce UI:

  1. Navigate to the Setup menu in Salesforce.
  2. Search for Scheduled Jobs in the Quick Find box and click on it.
  3. Locate the job you want to unschedule and click on the Del link next to it.

To unschedule a job programmatically, use the System.abortJob method:

AsyncApexJob jobInfo = [SELECT Id FROM AsyncApexJob WHERE JobType='Scheduled Apex' AND Status='Queued' LIMIT 1];
System.abortJob(jobInfo.Id);

Best Practices

  1. Error Handling: Implement error handling in your scheduled Apex class. The Database.setSavePoint and Database.rollback methods can be used to rollback database changes in case of errors.
  2. Test Coverage: Ensure your scheduled Apex classes have at least 75% test coverage.
  3. Bulkify your Code: Ensure your scheduled Apex class can handle more than one record at a time.
  4. Avoid Long-Running Transactions: Keep the execution time of your scheduled Apex class under the governor limit of 10 minutes.

That’s all! Now you should be able to create, schedule, monitor, and unschedule Apex jobs in Salesforce. Happy coding!

 

Mid Level Apex Tutorial

Speeding Up Apex Test Execution: A Guide for Faster Salesforce Deployments

Working with Time in Salesforce Apex

Salesforce Apex security best practices

Join the conversation

Your email address will not be published. Required fields are marked *

error: Content is protected !!