Sub topic 2
Scheduling a Job with `System.schedule`
This chapter assumes basic Apex classes, SOQL, DML, and governor limits. Scheduled Apex runs a class at a specified time. System.schedule creates the schedule in code and returns the new job ID.
Scheduling with `System.schedule`
A schedulable class implements Schedulable and defines execute. Pass three values to System.schedule: a job name, a cron expression, and an instance of the class.
public class EscalateStaleCases implements Schedulable {
public void execute(SchedulableContext context) {
List<Case> casesToEscalate = [
SELECT Id, Priority
FROM Case
WHERE IsClosed = false
AND Priority != 'High'
AND CreatedDate < LAST_N_DAYS:7
LIMIT 200
];
for (Case c : casesToEscalate) {
c.Priority = 'High';
}
update casesToEscalate;
}
}
// Seconds Minutes Hours Day_of_month Month Day_of_week
String cronExpression = '0 0 13 * * ?';
Id jobId = System.schedule(
'Escalate stale cases',
cronExpression,
new EscalateStaleCases()
);This expression runs every day at 1:00 PM in the Salesforce org's time zone. The question mark means that the day-of-week field is not specified.
Scheduling from Setup
You can create a schedule without Apex code that calls System.schedule:
- In Setup, search for Apex Classes.
- Select Schedule Apex.
- Choose the schedulable class.
- Enter a job name, start time, and frequency.
- Save the schedule.
Use code when deployment, version control, or dynamic scheduling matters. Use Setup for a simple administrator-managed timetable.
Identifying the Running Job
Salesforce passes a SchedulableContext object to execute. Its getTriggerId() method returns the ID of the current CronTrigger record.
public class LogScheduledRun implements Schedulable {
public void execute(SchedulableContext context) {
Id triggerId = context.getTriggerId();
System.debug('Running scheduled job: ' + triggerId);
}
}You can use this ID to query job details or correlate logs with a schedule.
Handing Large Workloads to Batch Apex
Scheduled Apex has the limits of one transaction. For large data volumes, let the scheduled class start Batch Apex. Each batch execution receives separate limits.
public class ArchiveOldTasksBatch
implements Database.Batchable<SObject> {
public Database.QueryLocator start(Database.BatchableContext context) {
return Database.getQueryLocator(
'SELECT Id FROM Task ' +
'WHERE IsClosed = true AND CreatedDate < LAST_N_DAYS:365'
);
}
public void execute(Database.BatchableContext context, List<Task> scope) {
delete scope;
}
public void finish(Database.BatchableContext context) {}
}
public class NightlyTaskCleanup implements Schedulable {
public void execute(SchedulableContext context) {
Database.executeBatch(new ArchiveOldTasksBatch(), 200);
}
}Exercise
Which method starts a scheduled Apex job, and what should you use for a very large data set?
Show answer
Use System.schedule to create the schedule. Start Batch Apex from the scheduled class for a very large data set.