12

Schedule Batch Class in APEX

Scheduled tasks can run data cleanup, a report or complex calculations in Salesforce. These repeat tasks often require an efficient recurrence method without manual intervention, and Salesforce Apex Scheduler and batch processing can provide that.

What Is a Schedule Batch Class In Apex?

In Apex, a Scheduled Batch Class is an automated procedure that lets you run a batch job at certain times or intervals without human involvement. It is accomplished by combining the Apex scheduler, which sets up the timing and frequency of execution, with the batch Apex’s ability to handle massive data volumes.

Use the Apex scheduler and the Schedulable interface if you have specific Apex classes that you want to run regularly or if you want to run a batch Apex job using the Salesforce user interface.

The scheduler runs as a system—all classes are executed, whether or not the user has permission to execute the class.

Important: Salesforce schedules the class for execution at the specified time. Actual execution may be delayed based on service availability.

Why Schedule a Batch Class in Apex?

The batch class could be useful for automating jobs you’d want to run periodically, say, nightly or weekly. For example:

  • Data Cleanup: Automatically remove or archive old records to keep the database clean.
  • Regular Data Updates: Performs mass updates of records within a specified periodic cycle.
  • Report Generation: Enables automatic compilation to create reports at the end of each day or week.

Through scheduling a batch class, you are assured that critical tasks will be performed automatically while freeing up time and resources for your team.

How to Schedule a Batch Class in Apex?

To schedule Batch Class using the Apex scheduler, you must perform the following steps:

  1. Implement the Schedulable interface in an Apex class that instantiates the class you want to run.
Code: global class MySchedulableClass implements Schedulable {
    global void execute(SchedulableContext sc) {
        // Instantiate the batch class
        MyBatchClass batch = new MyBatchClass();
        
        // Execute the batch class with a specified batch size (e.g., 100 records)
        Database.executeBatch(batch, 100);
    }
}
  1. Create the Batch Class because you’ll need a batch class to handle the data processing. This class implements the Database.Batchable interface.
Code: global class MyBatchClass implements Database.Batchable<SObject> {
    
    // Define the query for the batch
    global Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator(‘SELECT Id, Name FROM Account WHERE Status__c = \’Active\”);
    }

    // Define the operations to perform on each batch
    global void execute(Database.BatchableContext bc, List<SObject> scope) {
        for (SObject sObj : scope) {
            sObj.put(Status__c, ‘Updated’);
        }
        update scope;
    }

    // Define final actions after the batch completes
    global void finish(Database.BatchableContext bc) {
        System.debug(‘Batch processing completed.’);
    }
}
  1. From Setup, enter Apex Classes in the Quick Find box, select Apex Classes, and then click Schedule Apex.
  2. Specify the name of a class that you want to schedule.
  3. Specify how often the Apex class is to run.
  4. For Weekly—specify one or more days of the week the job is to run (such as Monday and Wednesday).
  5. For Monthly—specify either the date the job is to run or the day (such as the second Saturday of every month.)
  6. Specify the start and end dates for the Apex scheduled class. If you specify a single day, the job only runs once.
  7. Specify a preferred start time. The exact time the job starts depends on service availability.
  8. Click Save.

Note: You can only have 100 active or scheduled jobs concurrently. 

Alternatively, you can call the System.scheduleBatch method to schedule the batch job to run once at a future time.

Code: String cronExp = ‘0 0 2 * * ?’;  // Runs daily at 2 AM

System.schedule(‘Daily Batch Job’, cronExp, new MySchedulableClass());
Salesforce Developer Training CTA

Once the job has been completed, you can see specifics about the job (such as whether it passed or failed, how long it took to process, the number of records processed, and so on).

Next Chapter

Need more support?

Get a head start with our FREE study notes!

Learn more and get all the answers you need at zero cost. Improve your skills using our detailed notes prepared by industry experts to help you excel.

ServiceNow Stripe