Sub topic 12
Running Batches on a Schedule
This chapter assumes you can write a Database.Batchable class and start it with Database.executeBatch. It covers how to run that job automatically at set times.
Why a separate class
A batch class cannot be scheduled directly by cron. Salesforce schedules classes that implement the Schedulable interface. The usual pattern is a small scheduler class whose only job is to start the batch.
public class NightlyAccountRatingJob implements Schedulable {
public void execute(SchedulableContext sc) {
Database.executeBatch(new AccountRatingBatch(), 200);
}
}The execute method runs at the scheduled time. It queues the batch and returns quickly. The batch then runs as its own asynchronous job.
Registering the schedule
System.schedule takes a job name, a cron expression and a Schedulable instance. It returns the Id of the CronTrigger record.
// Run once to register the schedule: every day at 02:00
Id cronId = System.schedule(
'Nightly account rating',
'0 0 2 * * ?',
new NightlyAccountRatingJob()
);
System.debug('Scheduled with CronTrigger Id ' + cronId);Run this once, for example from Anonymous Apex. The schedule persists after that. Running it again with the same job name fails, because job names must be unique.
Reading the cron expression
The expression has these fields, in order:
| Field | Example | Meaning |
|---|---|---|
| Seconds | 0 | At second 0 |
| Minutes | 0 | At minute 0 |
| Hours | 2 | At 02:00 |
| Day of month | * | Every day |
| Month | * | Every month |
| Day of week | ? | No specific value |
| Year (optional) | omitted | Every year |
Use ? in either the day-of-month or day-of-week field, because you cannot constrain both at once. The time is based on the time zone of the user who scheduled the job.
Managing scheduled jobs
You can see scheduled jobs in Setup under Scheduled Jobs. You can also query them and remove them in code.
CronTrigger ct = [
SELECT Id, CronJobDetail.Name, NextFireTime, State
FROM CronTrigger
WHERE CronJobDetail.Name = 'Nightly account rating'
LIMIT 1
];
System.debug('Next run: ' + ct.NextFireTime);
System.abortJob(ct.Id);System.abortJob also works for cancelling a scheduled job. Do this before you register a changed schedule under the same name.
Common problems
- Overlapping runs. If a run is still going when the next one fires, you get two jobs on the same records. Make the query select only unprocessed records, as the rating example does with
Rating = null. - Queue limits.
Database.executeBatchfrom a scheduler can land in the Flex Queue when too many jobs are active. The scheduled job itself still succeeds. - Deployments. Salesforce blocks deploying a class that has pending scheduled jobs unless your org allows it. Abort the schedule first if a deployment fails for this reason.
- Testing. Scheduled jobs run only when
Test.stopTest()is called inside a test. Use a future date in your cron expression and assert on the outcome afterwards.
Exercise
Why does the scheduler class call Database.executeBatch instead of being the batch class itself, and what does the cron expression '0 30 6 ? * MON' mean?
Show answer
Salesforce schedules only classes that implement Schedulable, so a small scheduler starts the Batchable class. This keeps the batch reusable for manual runs and chaining. The expression means every Monday at 06:30.