In Salesforce, to Schedule Apex, you’d follow the steps below.
- Go to Setup, Apex Classes
- Click on Schedule Apex
- In this Screen, you have various options regarding the scheduling like the Class to schedule, the frequency of the run, etc.
Creating a Scheduled Class
You can use the below syntax to create an apex class for scheduling it for a later time.
global class scheduledMerge implements Schedulable {
global void execute(SchedulableContext SC) {
mergeNumbers M = new mergeNumbers();
}
}
Code Explanation
The above code has 2 main aspects that differentiate it from other apex classes.
- Schedulable interface
- execute method
Any piece of code inside execute method will be scheduled to run later.
Important Considerations While Developing an Apex Scheduler
- Salesforce schedules the apex class for execution at the specified time. Actual execution can be delayed based on service availability.
- You need to be very careful if you’re planning to schedule a class from an Apex trigger. You must always make sure that the trigger won’t add more scheduled classes than the allowed limit. Particularly, you should consider API bulk updates, import wizard, mass record changes through the user interface, and all those cases where bulk records can be updated at a given time
- For the purpose of best practices of a class, you need to break down methods as much as you can. Even though it’s possible to do all processing in the execute method, it’s recommended that all processing take place in a different class.
- Synchronous Web service callouts are not supported from scheduled Apex. For making asynchronous callouts, you can go with Queueable Apex or implementing the Database.AllowsCallouts marker interface.
Conclusion
In this way, if a piece of code needs to be run at a particular time in the future time to time, you can use Schedule Apex and use the scheduling feature to set the frequency of execution.
To learn more about Apex, check out some of my related blog posts below!
Additional Resources
- Apex Developer Guide: Apex Scheduler
- Salesforce Apex Trigger Events
- Salesforce Batch Apex
Cover Photo by Towfiqu barbhuiya on Unsplash