In this blog, we will discuss Schedule Apex in Salesforce with example. It is a type of asynchronous apex which used to run at a specific time. It runs in a separate thread.
For writing Schedular we need to implement a Schedulable interface to the class. The class which is implementing this interface has to define the execute method. It runs in the system mode, whether the user has permission or not to execute it.
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.
How to use Schedulable Apex?
Firstly, to use schedulable apex we need to implement a salesforce-provided interface i.e. Schedulable and need to define the execute method that this interface contains. It takes the SchedulableContext object as a parameter. Declare the implemented method as global or public.
Syntax:
Let’s understand Schedule Apex in Salesforce with an example
Scenario
Clean all opportunities which were closed 60 days ago.
ScheduleCleanOpportunity.apxc
To summarize, the provided code represents the apex class serving as an implementation of the Schedulable interface. Within the execute method, we retrieve opportunities closed within the past 60 days through a query utilizing the LAST_N_DAYS parameter.
How to execute Schedulable Apex?
We have two options for scheduling our apex:
- Schedule job from UI
- Using System.schedule
Let’s discuss both ways of scheduling
Schedule job from UI
We can schedule the job by following the below steps:
- Go to Setup
- Search for Apex as given in the below snapshot
3. In the apex class window. Click on Schedule Apex
In Schedule Apex provide the details mentioned, set the frequency for the scheduler whether it is weekly or monthly, start date and preferred time then hit the save button.
Using System.Schedule
Another way of scheduling our job is by doing it by programmatically way from execute an anonymous window in the developer console. We have to use the System.Schedule method to execute our Apex. It takes 3 parameters which are Job Name, CRON expression which represents the frequency and Class Instance.
Syntax
The above expression will schedule our job to run 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 below snapshot, we check that our next scheduled run is on 26 January which is Friday for this year (2024).
Let’s understand the CRON expression
Cron Expression is simple as this string ‘ * * * * ? *’. Now let’s explore it what its character means and what is the sequence
- Seconds : 0-59
- Minute : 0-59
- Hour (24 hour format) : 0-23
- Day of the month: 1-31
- Month: 1-12 or it can also represent like JAN, FEB and so on
- Day of the week: 1-7 or also can be represented like SUN, MON, TUE and so on.
- Optional year: null or 1970-2099
Want to Learn Salesforce Flows? Checkout our Salesforce Flow Course
From the above, except for seconds and minutes, all have some special characters which we can use to represent them. Let’s understand them one by one.
- (,) It is used to specify more than one value like MON, FRI
- (-) It specifies a range like JAN-FEB
- (*) It specified all values. If we use this value for a month then it will run for every month
- (?) It specifies no specific value. This option is only available for Day_of_month and Day_of_week.
- (/) It specifies the increment. like 1/6 so the number before the slash is the starting interval and the number after the slash is the interval amount.
- (L) It specifies the last value. Only available with Day_of_month and Day_of_week. For the Day_of_month it is the last day of the month and Day_of_week last day of the week is Saturday. For example, if we specify 3L that means last Tuesday.
- (W) It specifies the nearest weekday. Only available for Day_of_month.
- (#) It specifies the nth day of the month. Only available for the day of the week.
Note: Day_of_week and Day_of_month can’t be used simultaneously.
Things to remember while working with Schedule Apex:
- We can only have 100 scheduled jobs at one time.
- Use extreme care to use the scheduler from the trigger. It must not add more scheduled jobs than the limit.
- Synchronous web service callouts are not supported. Alternatively, we can asynchronous callout by using in future method and call that future from Schedular.
FAQ’s
1. What is a programmatic way of monitoring our scheduled jobs?
We can perform a query with our JobId on 2 objects which is CronJobDetail and CronTrigger to find out the count of our scheduled jobs like the below example;
2. How to schedule Batch classes by using the Scheduler class
Simply, we need to create the Batch class and then in the execute method of our Scheduler class, we need to execute our Batch class.
Syntax
Conclusion
In this blog, we discussed Schedule Apex in Salesforce with examples. Schedule Apex is a great way to perform the task weekly, monthly or regularly at a specified time.