Salesforce provides many ways to automate the business process to fulfill our requirements. It has many standard automation tools such as workflows, process Builders, approval processes, etc. Organizations may have very complex business functionality which cannot be fulfilled by the standard automation tools. To achieve complex functionalities, Salesforce provides a programming language called APEX for developers to build applications. You can create web services, email services, and perform complex validation over multiple objects etc. using Apex language.

In this article, we are going to see the step-by-step procedure on how to create an “Apex Scheduler”. If you want to run a piece of apex code at a particular time or at particular intervals of time we use Apex Scheduler. Apex scheduler is a class that runs at a regular interval of times.

Consider a Business scenario, an organization with the name ABC PVT LTD has a custom object called SAPOrders. When an order is converted to an invoice, the status of the Order will be marked as closed. The Organization wants to delete the closed orders every day at 10 PM as there are numerous records that convert to invoices every day. To achieve this, we will create a schedulable class that runs every day at 10 PM. The above scenario highlights how an Apex Scheduler works and when to use it. During working with APEX there can arise where a trigger can loop infinitely to cause a Recursive Trigger in Salesforce this should be avoided to prevent hitting the Governor Limit.

If you want Apex class to run like a schedule apex, it needs to implement the Schedulable Interface.

global class scheduledMerge implements Schedulable {

Any apex class that implements a schedulable interface has to define the execution method. Any logic or operation that you want to schedule should be defined inside the execute method.Connect-Salesforce-ERP

global void execute(SchedulableContext SC)

Once we create the apex class, we need to schedule it to specify the time in a specific pattern which is called a CRON expression. Below is the CRON Expression

Seconds Minutes Hours Day_of_month Month Day_of_week Optional_year

We use a few special characters to define the CRON Expression as follows:
• (,) Delimits values. For example, use JAN, MAR, APR to specify more than one month.
• (-) Specifies a range. For example, use JAN-MAR to specify more than one month.
• (*) Specifies all values.
• (?) Specifies no specific value.
• (/) Specifies increments.
• (L) Specifies the end of a range (last).
• (W) Specifies the nearest weekday (Monday-Friday) of the given day.
• (#) Specifies the nth day of the month, in the format weekday#day_of_month.

Are you ready to try our

Salesforce integration?

Creating a Schedulable Class to meet our Requirement:

1. Go to the Developer Console.
2. Click on File-> New -> Apex Class.
3. Enter the Name of the class. I’ve given SAPOrdersDeleteScheduler
4. A simple class with class name is generated. Implement the class with schedulable.
5. Following is the code to meet the above requirement.

global class SAPOrdersDeleteScheduler implements Schedulable {
global void execute(SchedulableContext sc){

List cldOrders = [select Id from SAPOrder__c where Status__c =’Closed’];
List cldOrderItems=[select Id from SAP_Order_Item__c where SAPOrder__c in:cldOrders];

delete cldOrderItems;
delete cldOrders;

6. In the above code, the operation is written in execute (SchedulableContext sc) method. Before we delete Orders (Parent), Order Items (Child) related to Order should be deleted. It contains two lists cldOrders(Contains list of Orders) and cldOrderItems(Contains List of Order Items related to cldOrders).

Are you ready to try our

Salesforce integration?

With the complexity of Apex, it’s ideal to follow the best practices while coding with it. You can follow our recommended top Salesforce Apex best practices to ensure a more intuitive experience. 

7. Following is the Test Class for SAPOrdersDeleteScheduler.

public class TestSAPOrdersDeleteScheduler {
static testmethod void testSAPOrdersDeleteScheduler(){
List cldOrders = new List();
SAPOrder__c so =new SAPOrder__c(Name = 'TestOrder', Status__c='Open');
insert cldOrders;
system.assertEquals('Open', so.Status__c);
List cldOrderitms = new List();
SAP_Order_Item__c oItms = new SAP_Order_Item__c(Name='Test OrderItem', SAPOrder__c =so.Id);
insert cldOrderitms;
so.Status__c = 'Closed';
update cldOrders;
SAPOrdersDeleteScheduler sch = new SAPOrdersDeleteScheduler();

8. Now we will schedule the SAPOrdersDeleteScheduler class to execute every day at 10 P.M. It can be scheduled in two ways.

a. Using Apex System.schedule(Name, CRONExpression, classObject)
b. Using UI

9. We will create using first method i.e. using Apex.

10. From developer console, navigate to “Open Execute Anonyms Window”. Below is the code to schedule SAPOrdersDeleteScheduler.

SAPOrdersDeleteScheduler sc = new SAPOrdersDeleteScheduler();
string cronExp = '0 0 22 * * ? *';
string JobId = system.schedule('Delete SAPOrders', cronExp, sc);


11. In the above code, we have created an object of SAPOrdersDeleteScheduler class and cronExp to schedule the class every day at 10 PM.

12. When System.schedule(‘Delete SAPOrders’, cronExp, sc) is executed a job is created and the id is stored in JobId.

13. We can monitor the scheduled Jobs by navigating to SetUp-> Monitor-> Jobs-> Schedule Jobs. Following is the job we have created in the above step.all-scheduled-jobs-apex-scheduler-in-salesforce

Are you ready to try our

Salesforce integration?

Apex Scheduler Limits:

1. You can only have 100 scheduled Apex jobs at one time.
2. The maximum number of scheduled Apex executions per a 24-hour period is 250,000 or the number of user licenses in your organization multiplied by 200, whichever is greater.

In this way, you can schedule apex classes to execute at particular intervals of time by implementing the schedulable class. Sometimes, execution may be delayed based on service availability.

Now, you can easily integrate your Salesforce CRM with back-end ERP systems to remove manual data entry and automate the business process!Connect-Salesforce-ERP