How to Schedule the Apex in Salesforce?

AMIT SINGH
6 min readNov 6, 2022

--

Scheduling the Apex Class Specially Batch Apex is very important for any business. We will see what are the various options to schedule any Apex Class in Salesforce and how to track any scheduled job.

Schedulable Interface in Salesforce

When you wanted to schedule any apex class within Salesforce you have to implement an interface in the same class or Create a new Class that will implement the Schedulable Interface and will also implement the body of execute method.

Below is the simple scheduler class

global class SimpleSchedulerClass implements Schedulable {
global void execute(SchedulableContext SC) {
}
}

The above class is just a skeleton of the Schedulable Apex Class.

Now you can use any code withing execute a method and the execute method will execute every type your schedulable apex call runs.

Within the execute method you can call the method of any batch apex, queueable or any simple apex class.

Requirement

We talked about what is Schedulable interface and the method which will always be there when you implement the interface.

Now, let’s create an Apex class that will process some account records.

Note: — We will not put the logic within the Apex Class.

public with sharing class AccountProcessor {
public static void processInActiveAccounts(){
System.debug('inside processInActiveAccounts method >>> ');
}
}

Schedulable Apex Class in Salesforce

We have created the apex class AccountProcessor with one method that will process some inactive accounts.

The requirement is to schedule the apex class which will run daily at 11:30 PM.

To Schedule the apex class we need to create a schedulable apex class.

We have 2 options here that we can use to create a Schedulable apex class

  1. Create a Separate apex class
  2. Make the AccountProcessor class act as a schedulable apex class

Let’s create a separate apex class that will implement the schedulable interface

public with sharing class AccountProcessorSchedulable implements System.Schedulable {
public void execute(System.SchedulableContext scheduleContext){
// Call the AccountProcessor class method here
AccountProcessor.processInActiveAccounts();
}
}

In the above apex class we have implemented the Schedulable interface and also implemented the execute method.

If you wanted to test from the anonymous window you can use the below code

AccountProcessorSchedulable schedulable = new AccountProcessorSchedulable();
schedulable.execute(null);

Schedule Apex Class

Now, you have created the Apex Class, created the scheduled class, and done the testing. You wanted to schedule the apex class to monitor and be sure that your apex class is working fine.

To Schedule the apex class there are two ways

  1. Schedule from Interface
  2. Schedule using the CRON expression

–> We use the first option when we have straightforward scheduling like every day, every week.

–> We use the CRON Expression when we have a requirement to schedule the class every hour, every 30 minutes, and many more complex schedules.

Let’s see how we can schedule the above apex class using interface

  • Login to Salesforce
  • From the quick search box search for “Apex Class”
  • Click on the Apex Class under Custom Code
  • Click on the Schedule Apex button
  • Provide the Job Name
  • Selected your Apex class from Lookup ( When you will click on lookup you will see all the schedulable classes there and select your own )
  • For frequency, Select Weekly and select All days
  • For the Start Date select today’s date
  • For End date select any future date and click save

Schedule Apex Class using Interface

Create Scheduled Job

Select Schedulable Apex Class

Select Schedulable Apex Class

List All Scheduled Jobs

In the previous step, you successfully scheduled the apex job. Now, as a developer or admin, you wanted to see what are all the scheduled jobs.

To list all the scheduled jobs you can follow the below steps

  • Login to Salesforce
  • In the quick search for “Jobs
  • Select Scheduled Jobs under Environments
  • This will list all the scheduled jobs, refer screenshot

How to list all schedule jobs using SOQL

Sometimes, there is a requirement to list all the jobs using apex via SOQL and display them in UI components either with the help of LWC or VF, or Aura Components.

To get all the scheduled jobs using SOQL we need to make a query on the ApexAsyncJob object which is a standard object and available in every salesforce org.

Below is the query that you can use to list all the scheduled jobs

SELECT
ApexClass.Name,
Id,
JobItemsProcessed,
JobType,
Status,
NumberOfErrors,
MethodName,
CronTrigger.CronJobDetail.Name
FROM
AsyncApexJob
WHERE
JobType IN ('BatchApexWorker', 'ScheduledApex')

If you wanted to know about the specific class if the job is scheduled or not. You can add the filter in the same query in the last add AND ApexClass.Name = ‘AccountProcessorSchedulable‘

Below is the query for the same

SELECT
ApexClass.Name,
Id,
JobItemsProcessed,
JobType,
Status,
NumberOfErrors,
MethodName,
CronTrigger.CronJobDetail.Name
FROM
AsyncApexJob
WHERE
JobType IN ('BatchApexWorker', 'ScheduledApex')
AND ApexClass.Name = 'AccountProcessorSchedulable'

How to get Success/Error details about the specific job

Say that you have so many scheduled jobs in Salesforce and you wanted to check the status of a particular class.

To get the error or success message we can use SOQL like the below

SELECT
ApexClass.Name,
Id,
JobItemsProcessed,
JobType,
Status,
NumberOfErrors,
MethodName,
ExtendedStatus
FROM
AsyncApexJob
WHERE
JobType IN ('BatchApexWorker', 'ScheduledApex')
AND ApexClass.Name = 'AccountProcessorSchedulable'

In the result of the above query, the ExtendedStatus column will contain the Error Message if there are any.

How to make callout using Schedulable Apex?

Suppose that you have a requirement to make the external Callout using Schedulable Apex or from the Apex class that is scheduled.

Directly, you can not make the callout from the Schedulable Class, If you want you have to implement another interface in either the schedulable class or in the main class.

Here is the example for the same

public with sharing class AccountProcessor implements Database.AllowsCallouts {
public static void processInActiveAccounts(){
System.debug(System.LoggingLevel.DEBUG, 'inside processInActiveAccounts method >>>>');
}
}

Database.AllowsCallouts is the interface we must implement if we wanted to make callouts from the Schedulable Class or Batch Class.

Modify the apex class which is scheduled

In most of the cases, we found that we need a modification or tweaks in the Apex Class which is scheduled, or the class which is being called from the Scheduler class.

If we try to modify the class which is scheduled we will get the below error

This schedulable class has jobs pending or in progress

So how can we modify the class after the class is scheduled?

We have 2 options for this and those are given below

  1. Delete the Scheduled job, Modify it and Schedule it again
  2. You can bypass this error by allowing deployments with Apex jobs in the Deployment Settings page in Setup.

To bypass the deployment while the job is scheduled you can follow the below steps

  • Login to Salesforce
  • Search for “Deployment” in Quick Search
  • Select “Deployment Settings” under the environment
  • Enable “Allow deployments of components when corresponding Apex jobs are pending or in progress.” checkbox
  • Click on Save

Note: — this is not recommended way because the existing scheduled jobs are in progress status or in pending status and might fail.

Check the below screenshot for the reference

How to Schedule Apex Using CRON Expression

I have posted a blog post where we talked about how we can schedule the batch apex for every hour or every 5 minutes.

You can use the same concept to schedule any class.

Here is the link

Resources

While developing this blog post, I have referred to the below documents by Salesforce

Feedback is really appreciated.

--

--

AMIT SINGH

Software Developer by day & YouTube by night. Salesforce Architect || Salesforce MVP || Integration Expert