Ora

How to Schedule a Batch Class in Salesforce?

Published in Salesforce Automation 6 mins read

Scheduling a batch class in Salesforce allows you to run complex, long-running processes that deal with large volumes of data outside of regular business hours or at predetermined intervals. There are two primary methods to schedule a batch class: through the Salesforce user interface (UI) or programmatically using Apex code.

Understanding Salesforce Batch Classes

A Salesforce batch class, implementing the Database.Batchable interface, is designed to process records in batches, preventing governor limits from being hit when dealing with large datasets. While a batch class itself handles the data processing, it often needs a "scheduler" to initiate its execution at a specific time or on a recurring basis. This scheduler is typically a separate Apex class that implements the Schedulable interface.

Method 1: Scheduling a Batch Class via the Salesforce User Interface

The Salesforce UI provides a straightforward way to schedule an Apex class that implements the Schedulable interface. This method is ideal for administrators or developers who prefer a visual setup without writing additional deployment scripts.

Step-by-Step Guide:

  1. Navigate to Apex Classes: From Salesforce Setup, use the Quick Find box to search for "Apex Classes" and select it.
  2. Access Schedule Apex: On the Apex Classes page, click the Schedule Apex button.
  3. Define Job Details:
    • Job Name: Enter a descriptive name for your scheduled job (e.g., "Daily Account Cleanup Batch").
    • Apex Class: Click the lookup icon and select the Apex class that implements the Schedulable interface and in turn, calls your batch class.
    • Preferred User: Choose the user under whose context the scheduled job will run. This user must have the necessary permissions to execute the Apex class and perform any data operations.
    • Frequency: Specify how often the Apex class should run.
      • Weekly: Select one or more specific days of the week (e.g., Monday and Wednesday).
      • Monthly: Choose a specific date of the month (e.g., the 1st or 15th) or a specific day of the week (e.g., the first Monday).
    • Start/End Date: Define the date range for the job's execution.
    • Preferred Start Time: Select the hour at which the job should begin.
  4. Save the Schedule: Click Save to activate your scheduled job.

Example of a Schedulable Class for a Batch:

Before you can schedule via the UI, you need an Apex class that implements Schedulable and calls your batch class.

// MySimpleBatchClass.apxc - Your actual batch logic
public class MySimpleBatchClass implements Database.Batchable<SObject>, Database.Stateful {
    public Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator('SELECT Id, Name FROM Account WHERE LastModifiedDate < LAST_N_MONTHS:6');
    }

    public void execute(Database.BatchableContext BC, List<Account> scope) {
        List<Account> accountsToUpdate = new List<Account>();
        for (Account acc : scope) {
            acc.Description = 'Processed by batch';
            accountsToUpdate.add(acc);
        }
        update accountsToUpdate;
    }

    public void finish(Database.BatchableContext BC) {
        System.debug('MySimpleBatchClass finished!');
    }
}

// MyBatchScheduler.apxc - The class you schedule via UI or programmatically
public class MyBatchScheduler implements Schedulable {
    public void execute(SchedulableContext SC) {
        MySimpleBatchClass myBatch = new MySimpleBatchClass();
        Database.executeBatch(myBatch, 200); // Execute in batches of 200 records
    }
}

You would select MyBatchScheduler in the "Apex Class" field when scheduling via the UI.

Method 2: Programmatic Scheduling using Apex Code

For more dynamic or automated scheduling, you can use Apex code to schedule a class that implements the Schedulable interface. This is often used for deployment automation, complex scheduling logic, or when you need to schedule a job from within another Apex context.

Implementing the Schedulable Interface:

As shown in the example above, your scheduling class must implement the Schedulable interface and provide an implementation for its execute method. This execute method is where you instantiate and call your batch class.

// MyBatchScheduler.apxc (same as above)
public class MyBatchScheduler implements Schedulable {
    public void execute(SchedulableContext SC) {
        MySimpleBatchClass myBatch = new MySimpleBatchClass();
        Database.executeBatch(myBatch);
    }
}

Using System.schedule Method:

Once you have your Schedulable class, you can schedule it using the System.schedule method. This method requires three arguments: a job name, a cron expression, and an instance of your Schedulable class.

String jobName = 'Schedule My Daily Account Batch';
String cronExpression = '0 0 1 * * ?'; // Runs every day at 1:00 AM
MyBatchScheduler scheduler = new MyBatchScheduler();
System.schedule(jobName, cronExpression, scheduler);

You can execute this System.schedule call from the Developer Console's Anonymous Apex window or within another Apex class or trigger if appropriate.

Understanding Cron Expressions:

Cron expressions are powerful strings used to define the schedule for your job. They consist of seven fields, representing different time units:

Field Description Allowed Values Wildcards
1 Seconds 0-59 *, -, ,, /
2 Minutes 0-59 *, -, ,, /
3 Hours 0-23 *, -, ,, /
4 Day of Month 1-31 *, ?, -, ,, /, L, W
5 Month 1-12 or JAN-DEC *, -, ,, /
6 Day of Week 1-7 or SUN-SAT *, ?, -, ,, /, L, #
7 Year (Optional) *, -, ,, /

Common Cron Expression Examples:

  • 0 0 1 * * ?: Every day at 1:00 AM.
  • 0 30 22 * * ?: Every day at 10:30 PM.
  • 0 0 0 ? * MON-FRI: Every weekday (Monday-Friday) at midnight.
  • 0 0 12 1 * ?: On the 1st day of every month at 12:00 PM (noon).
  • 0 0 10 ? * 1#3: On the third Sunday of every month at 10:00 AM.

For more details on cron expressions, refer to the Salesforce Apex Developer Guide.

Monitoring Scheduled Jobs

Regardless of how you schedule your batch class, you can monitor and manage all scheduled jobs in Salesforce:

  1. From Setup, enter "Scheduled Jobs" in the Quick Find box and select Scheduled Jobs.
  2. On this page, you can view the status, submitter, submitted date, and the next run time for all scheduled Apex jobs.
  3. You can also delete (abort) a scheduled job from this list if you no longer need it to run. This is crucial for managing long-running or incorrectly configured jobs.

Key Considerations for Scheduling Batch Classes

  • Governor Limits: Batch Apex helps manage limits, but be mindful of CPU time, heap size, and total query rows across all batches.
  • Time Zones: Cron expressions and UI scheduling times are based on the organization's default time zone.
  • Error Handling: Implement robust error handling within your batch class and consider logging mechanisms to capture any failures.
  • Idempotency: Design your batch class to be idempotent, meaning running it multiple times with the same input yields the same result, preventing unintended data corruption.
  • Security Context: Ensure the "Preferred User" for UI scheduling or the user executing System.schedule has appropriate permissions.

By following these methods and best practices, you can effectively schedule your batch classes to automate essential data processing tasks in Salesforce.