Scheduled Apex
What is Scheduled Apex?
Scheduled Apex allows developers to automate repetitive tasks, which saves time and reduces the risk of errors.
it allows to execute Apex code at specific intervals or on a particular schedule
It enables to run Apex classes at making it ideal for daily or weekly maintenance tasks using Batch Apex.
It’s useful for automating tasks that need to run periodically, such as data cleanup, sending reports, or updating records.
Benefits of Scheduled Apex
Automation:
Scheduled Apex allows developers to automate repetitive tasks, saving time and reducing the risk of errors. Examples include updating records, sending emails, and running reports1.
Scalability:
It can handle large-scale tasks, such as updating thousands of records or running complex reports.
Customization:
You can tailor scheduled jobs to your specific business needs, ensuring they align with your organization’s processes.
Flexibility:
Scheduled Apex lets define when tasks run—daily, weekly, or at other intervals. have control over execution timing.
Improved Efficiency:
By automating routine processes, can free up resources for more critical tasks.
Cost Savings:
Reduced manual effort leads to cost savings in the long run
Use Cases
Data Cleanup:
This involves removing outdated or unnecessary records from your database. Examples: Deleting old customer records, archiving historical data, or cleaning up unused files.
Notifications:
Sending alerts or reminders to users. Examples: Reminding customers of upcoming appointments, notifying employees of pending tasks, or sending automated emails.
Aggregations:
Calculating summary data from large datasets. Examples: Summing up sales revenue, finding average scores, or counting the number of orders.
Integration:
Syncing data between different systems or applications. Examples: Connecting your CRM with an email marketing tool, integrating e-commerce data with inventory management, or sharing data between Salesforce and an external database.
Syntax
To schedule an Apex class to run at specific times in Salesforce, follow these steps:
Implement the Schedulable Interface: First, create an Apex class that implements the Schedulable interface. The Schedulable interface contains a single method called execute, which you must implement. Here’s the basic syntax:
public class MyScheduledClass implements Schedulable { public void execute(SchedulableContext sc) { // Your code here } }
Schedule the Class: To schedule your class, use the System.schedule method. It accepts three parameters:
Job name (a descriptive name for your scheduled job)
Cron expression (specifies when the job should run)
An instance of your Schedulable class
Example:
MyScheduledClass myJob = new MyScheduledClass(); String cronExpression = '0 0 13 ?'; // Runs every day at 1:00 PM String jobId = System.schedule('My Scheduled Job', cronExpression, myJob);
The System.schedule method schedules the job with the specified cron expression.