Scheduled Apex
What is Scheduled Apex?
Scheduled Apex lets you run Apex code automatically at a specific time — daily, weekly, monthly, or even hourly.
For example:
you can run a batch job every day at 7:00 AM
Or clear old records every Sunday night
It’s like setting an alarm for Apex code!
Structure of a Scheduled Class
To create a scheduled class, you must implement the Schedulable interface and define the execute() method:
apex
global class YourSchedulerClass implements Schedulable {
global void execute(SchedulableContext sc) {
// Logic to run on schedule
}
}
Example: Schedule Contact Batch Job Daily at 7 AM
Business Need:
We want to run the ContactBatchUpdate batch job automatically every day at 7 AM.
Code (Scheduler Class):
apex
global class ContactBatchScheduler implements Schedulable {
global void execute(SchedulableContext sc) {
// Create batch object
ContactBatchUpdate batch = new ContactBatchUpdate();
// Run the batch with batch size 200
Database.executeBatch(batch, 200);
}
}
How to Schedule This Job:
Paste this in the Anonymous Window to schedule it:
apex
String cronExp = ‘0 0 7 * * ?’; // Every day at 7 AM
String jobName = ‘Daily Contact Update Batch’;
ContactBatchScheduler sch = new ContactBatchScheduler();
System.schedule(jobName, cronExp, sch);
Cron Expression Breakdown
Position | Value | Meaning |
---|---|---|
1 | 0 | Seconds |
2 | 0 | Minutes |
3 | 7 | Hours (7 AM) |
4 | * | Day of month |
5 | * | Month |
6 | ? | Any Day (Week) |
Cron Expression Format:
Seconds Minutes Hours Day Month DayOfWeek
Code Explanation:
Part | Description |
---|---|
ContactBatchScheduler | This is your scheduled class. |
execute() | This method runs when the schedule triggers. |
System.schedule() | Schedules the class with a CRON expression. |
‘0 0 7 * * ?’ | Means “run every day at 7 AM”. |
Output:
Every day at 7:00 AM, Salesforce will:
1.Run the ContactBatchUpdate class.
2.Update all Contact records’ Description to “Updated by Batch” — automatically.
Best Practices
• Give meaningful names to classes and jobs.
• Don’t write too many SOQL/DML statements inside execute().
• Use Test.startTest() and Test.stopTest() in test classes.
• Use try-catch to handle errors safely.
• Don’t schedule too many jobs — monitor limits!