12

Schedule Batch Class in APEX

Scheduled tasks can be used to run data cleanup operations, generate reports, or perform complex calculations in Salesforce. These repeat tasks often require an efficient recurrence method without manual intervention, and Apex Scheduler, in combination with Batch Apex, can provide that.

What Is a Schedule Batch Class In Apex?

Schedule batch class in Apex is a design pattern where a schedulable class triggers a batch Apex job at defined 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 to handle massive data volumes.

Use the Schedulable interface when you want to run Apex classes at specific times or intervals, either programmatically or via the Salesforce UI. 

Scheduled Apex runs in system mode, but it executes under the context of the user who scheduled the job. Object permissions are generally bypassed, but sharing rules depend on whether the class is declared with or without sharing.

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?

A batch class is useful for automating tasks that need to run periodically, say, nightly or weekly. The schedulable apex class 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 schedule.
  • 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?

In the batch apex scheduling tutorial in Apex scheduler, the following steps include:

  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.
global class MyBatchClass implements Database.Batchable { // 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 scope) { List accountsToUpdate = new List(); for (SObject sObj : scope) { Account acc = (Account)sObj; acc.Status__c = 'Updated'; accountsToUpdate.add(acc); } update accountsToUpdate; } // 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 Apex jobs concurrently. This limit applies to active scheduled jobs in the system.

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

CRON Expression Salesforce 

The CRON expression is used with the System.schedule method to automate Apex jobs at a specific time. The CRON expression Salesforce example

The string ‘0 0 2 * * ?’ means:

  • 0 – Seconds at 0 seconds
  • 0 – Minutes at 0 minutes
  • 2 – Hours at 2 AM
  • * – Day of Month (Every day)
  • * – Month (Every Month)
  • ? – Day of week (required when day of month is specified)
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 view details such as execution status, processing time, and 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.

Frequently Asked Questions

What is a scheduled batch class in Apex?

A schedule batch class in Apex is an Apex class that combines batch Apex functions with a schedulable interface. It helps developers to run complex, long-running processes on multiple records at scheduled times.

How do I schedule a batch job in Salesforce?

To schedule a batch job in Salesforce by implementing the Database.Batchable interface and use the Apex scheduler to run at specific times.

What is a cron expression in Salesforce?

A cron expression in Salesforce is a string of characters that is used to define a specific schedule for running an Apex class that implements the schedulable interface.

How many scheduled jobs are allowed in Apex?

Maximum 100 concurrent scheduled Apex jobs in Salesforce organization, with limit reduced to 5 in Developer Edition orgs.

Book Free15-Minutes Career Counselling