Scheduler Apex in Salesforce With Examples : Bijay Kumar
by: Bijay Kumar
blow post content copied from SalesForce FAQs
click here to view original post
### Summary of Scheduler Apex in Salesforce Scheduler Apex in Salesforce is a feature that allows you to automatically run Apex classes at specified times, similar to scheduled triggers. This is particularly useful for tasks like data cleanup, batch processing, and generating reports without needing manual intervention. **Key Details:** - **Definition**: Scheduler Apex is a type of asynchronous Apex that automates the execution of Apex classes. - **Implementation**: To use it, you need to implement the `Schedulable` interface in your Apex class. The class must be declared as `global`, and it requires an `execute()` method. - **Use Cases**: Common uses include deleting old records, sending notifications, and performing regular maintenance tasks. - **Example**: An example provided is an Apex class that deletes opportunities closed more than 50 days ago, scheduled to run weekly. **How to Schedule Apex**: 1. **From Salesforce UI**: You can schedule an Apex class through the Salesforce Lightning UI by navigating to Apex Classes, clicking "Schedule Apex," and filling in the required details such as job name, class, frequency, and timing. 2. **Using System.Schedule() Method**: You can also schedule jobs programmatically using the `System.Schedule` method, which requires a job name, a CRON expression for frequency, and an instance of the class. ### Additional Context Scheduler Apex is essential for maintaining data integrity and automating repetitive tasks in Salesforce, which can save time and reduce errors. By leveraging this feature, organizations can ensure that critical operations are performed consistently and efficiently. ### Hashtags for SEO #Salesforce #Apex #SchedulerApex #SalesforceDevelopment #Automation #DataCleanup #BatchProcessing #SalesforceTutorial #CloudComputing #CRM
Like the scheduled trigger flow in Salesforce, when we want to set a specific time to execute the apex class, we have a scheduler apex in Salesforce, which we can use to schedule the apex class in Salesforce.
In this tutorial, we will learn about scheduler apex in Salesforce with examples. In that, I will explain what scheduler apex is in Salesforce, their methods, and how to use a schedule apex in Salesforce.
What is Scheduler Apex in Salesforce?
The schedule apex is a type of asynchronous apex that enables the automated execution of Apex classes at specified times. By implementing the Schedulable interface in an Apex class, we can define daily operations like data cleanup or batch processing. This feature ensures that critical tasks are performed regularly without manual intervention, enhancing efficiency.
It is very useful to perform daily tasks such as data cleanup or any other logic that needs to be run at a particular time. We can call batch apex inside the schedular to perform operations on large data sets to avoid hitting the governor limit.
Syntax: Scheduler Apex
global class Class_Name implements Schedulable {
global void execute ( SchedulableContext SC ) {
}
}
- Schedulable: In Salesforce, the apex class implements the schedulable interface, which allows it to be scheduled for execution at a specific time.
- Global: The class must be global because it implements the schedulable interface, and Salesforce requires scheduled apex classes to be accessible system-wide.
- Execute(): is the required method when implementing schedulable.
- SchedulableContext SC: This parameter provides context about the scheduled execution, but it is rarely used.
When to Use Scheduler Apex in Salesforce?
- The scheduler apex is used to execute tasks at a specified time. So we can automate periodic tasks like batch processing.
- We can run maintenance jobs to reduce the number of records displayed in the object, such as archiving old records.
- Also, we can schedule the reports or send notifications using the scheduler apex.
Example: Create Scheduler Apex in Salesforce
Now, I will explain step by step how to create a scheduler apex by implementing the schedulable interface and how to execute it in Salesforce.
For example, If any opportunities which were closed 50 days ago, then we need to delete all those opportunities. After that, every week, it should check if any opportunity was closed 50 days ago, then the apex class should execute, and the opportunity should get deleted.
Before creating the scheduler apex, let’s check the opportunities that were closed 50 days ago. Now, we want to delete these opportunities.

Here, I created the Apex class DeleteOpportunities, a scheduled Apex class implemented to delete closed opportunities that were closed within the last 50 days.
global class DeleteOpportunities implements Schedulable {
public void execute( SchedulableContext ctx ) {
List<Opportunity> oppoList = [ SELECT Name, StageName, CloseDate FROM
Opportunity WHERE IsClosed = True AND CloseDate = LAST_N_DAYS:50 ];
try{
if( oppoList != null && oppoList.size() > 0) {
DELETE oppoList;
}
}
catch( Exception e ){
System.debug( 'Error occurred while deleting opportunities ' +e.getMessage());
}
}
}
Now, let’s understand the implementation of the scheduled apex class. Below, I have explained step by step how we implemented and executed the apex class.
In the above apex class, we declared it as global, and it implemented a Schedulable interface. In that, we declared the execute() method, which is required when implementing Schedulable. Then, the system calls this method when the scheduled job runs.
In the method, we declared a list collection that retrieves closed opportunities (IsClosed = True) and has a CloseDate within the last 50 days.
After that, using exception handling(try, catch blocks), we checked whether the list we had records and deleted all records that we had in the list. If any error occurs, the catch block handles the error and logs an error message if something goes wrong.
How to Execute Scheduler Apex in Salesforce
There are two ways to execute the scheduler apex in Salesforce. Below, I have explained both options for scheduling our apex:
- Schedule Apex Class from Salesforce UI
- Using System.Schedule() Method in Apex.
1. Schedule Apex Class from Salesforce UI
In the following steps, I have explained how we can schedule an apex class from Salesforce Lightning UI.
1. Go to Setup -> in Quick Find, search for ‘Apex Classes‘. -> Click on it.

2. In the Apex Classes, click the Schedule Apex button to execute the Apex class at a specific time interval.

3. To schedule the apex class, we need to provide the following details:
- Job Name: Provide the job name. It should be in API name format.
- Apex Class: Select the apex class that you want to schedule.
- Schedule Using: Here, we have selected a schedule builder.
- Frequency: There are two options to select a frequency.
- Weekly: If you select weekly, then you need to select any day from the week so that the class will execute on the chosen day.
- Monthly: Here, you need to select any days from the month. So that on the chosen day, the class can execute.
- Start Date: Select the start date from when you want to schedule the apex class.
- End Date: The end date will be the last date to execute the scheduled apex.
- Preferred Start Time: Select the time so the class executes at the selected time and date.
After that, click the Save button to schedule the apex class.

To view the scheduled apex class in the Quick Find, search for the Apex Classes. Click on it. In the below image, you can see the class we selected in the schedule apex. Then, in the Job Type, we have Scheduled Apex.

Again, as you write a query to retrieve the records that were closed 50 days ago, then you will get nothing because, using the scheduler ape,x, we already deleted those records.

2. Using System.Schedule() Method in Apex
Another way of scheduling the job is by programmatically executing an anonymous window in the developer console. We have to use the System.Schedule method to execute our Apex. It takes three parameters: job name, CRON expression, which represents frequency, and class instance.
Syntax:
DeleteOpportunities DelOppo = new DeleteOpportunities ();
String str = ' 0 0 12 ? * FRI ' ;
String jobID = System.schedule( ' Delete closed opportunities ', str, DelOppo );
The above expression will schedule an apex class every Friday at 12 pm. We can also monitor our job by navigating to Scheduled Job in the Quick Find box from Setup.
In the image below, we can see that our Next Scheduled Run is on 14 February, which is Friday for this year(2025).

Conclusion
I hope now you have got an idea about the scheduler apex in Salesforce with examples. In that, I have explained what scheduler apex is in Salesforce, its syntax, and when to use it. After that, using the scenario, I explained how to create a scheduler apex and execute it from the scheduler job and system.Schedule() method in Apex.
You may like to read:
- Apex Triggers in Salesforce
- How to Create and Use Constructors in Salesforce Apex Classes
- Batch Apex in Salesforce With Examples
- How to Handle Events in Salesforce Lightning Web Components?
The post Scheduler Apex in Salesforce With Examples appeared first on SalesForce FAQs.
February 11, 2025 at 10:58AM
Click here for more details...
=============================
The original post is available in SalesForce FAQs by Bijay Kumar
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Post a Comment